7bfb9946
tangwang
向量化模块
|
1
2
3
|
"""
Embedding service (FastAPI).
|
ed948666
tangwang
tidy
|
4
|
API (simple list-in, list-out; aligned by index):
|
7a013ca7
tangwang
多模态文本向量服务ok
|
5
6
7
|
- POST /embed/text body: ["text1", "text2", ...] -> [[...], ...] (TEI/BGE,语义检索 title_embedding)
- POST /embed/image body: ["url_or_path1", ...] -> [[...], ...] (CN-CLIP 图向量)
- POST /embed/clip_text body: ["短语1", "短语2", ...] -> [[...], ...] (CN-CLIP 文本塔,与 /embed/image 同空间)
|
7bfb9946
tangwang
向量化模块
|
8
9
|
"""
|
0a3764c4
tangwang
优化embedding模型加载
|
10
|
import logging
|
07cf5a93
tangwang
START_EMBEDDING=...
|
11
|
import os
|
4747e2f4
tangwang
embedding perform...
|
12
|
import pathlib
|
7bfb9946
tangwang
向量化模块
|
13
|
import threading
|
efd435cf
tangwang
tei性能调优:
|
14
|
import time
|
4747e2f4
tangwang
embedding perform...
|
15
|
import uuid
|
efd435cf
tangwang
tei性能调优:
|
16
17
|
from collections import deque
from dataclasses import dataclass
|
b2dff38f
tangwang
embedding-image接口...
|
18
|
import tempfile
|
7bfb9946
tangwang
向量化模块
|
19
20
21
|
from typing import Any, Dict, List, Optional
import numpy as np
|
b2dff38f
tangwang
embedding-image接口...
|
22
|
import requests
|
4747e2f4
tangwang
embedding perform...
|
23
24
|
from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.concurrency import run_in_threadpool
|
7bfb9946
tangwang
向量化模块
|
25
|
|
7214c2e7
tangwang
mplemented**
|
26
|
from config.env_config import REDIS_CONFIG
|
4747e2f4
tangwang
embedding perform...
|
27
|
from config.services_config import get_embedding_backend_config
|
5a01af3c
tangwang
多模态hashkey调整:1. 加...
|
28
29
30
31
32
|
from embeddings.cache_keys import (
build_clip_text_cache_key as _mm_clip_text_cache_key,
build_image_cache_key as _mm_image_cache_key,
build_text_cache_key,
)
|
7bfb9946
tangwang
向量化模块
|
33
|
from embeddings.config import CONFIG
|
c10f90fe
tangwang
cnclip
|
34
|
from embeddings.protocols import ImageEncoderProtocol
|
7214c2e7
tangwang
mplemented**
|
35
|
from embeddings.redis_embedding_cache import RedisEmbeddingCache
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
36
37
38
39
40
41
42
|
from request_log_context import (
LOG_LINE_FORMAT,
RequestLogContextFilter,
bind_request_log_context,
build_request_log_extra,
reset_request_log_context,
)
|
7bfb9946
tangwang
向量化模块
|
43
|
|
a7920e17
tangwang
项目名称和部署路径修改
|
44
|
app = FastAPI(title="saas-search Embedding Service", version="1.0.0")
|
7bfb9946
tangwang
向量化模块
|
45
|
|
4747e2f4
tangwang
embedding perform...
|
46
|
|
4747e2f4
tangwang
embedding perform...
|
47
48
49
50
51
52
|
def configure_embedding_logging() -> None:
root_logger = logging.getLogger()
if getattr(root_logger, "_embedding_logging_configured", False):
return
log_dir = pathlib.Path("logs")
|
4747e2f4
tangwang
embedding perform...
|
53
|
log_dir.mkdir(exist_ok=True)
|
4747e2f4
tangwang
embedding perform...
|
54
55
56
|
log_level = os.getenv("LOG_LEVEL", "INFO").upper()
numeric_level = getattr(logging, log_level, logging.INFO)
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
57
58
|
formatter = logging.Formatter(LOG_LINE_FORMAT)
context_filter = RequestLogContextFilter()
|
4747e2f4
tangwang
embedding perform...
|
59
60
|
root_logger.setLevel(numeric_level)
|
41856690
tangwang
embedding logs
|
61
62
63
64
|
root_logger.handlers.clear()
stream_handler = logging.StreamHandler()
stream_handler.setLevel(numeric_level)
stream_handler.setFormatter(formatter)
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
65
|
stream_handler.addFilter(context_filter)
|
41856690
tangwang
embedding logs
|
66
|
root_logger.addHandler(stream_handler)
|
4747e2f4
tangwang
embedding perform...
|
67
68
69
70
|
verbose_logger = logging.getLogger("embedding.verbose")
verbose_logger.setLevel(numeric_level)
verbose_logger.handlers.clear()
|
41856690
tangwang
embedding logs
|
71
72
|
# Consolidate verbose logs into the main embedding log stream.
verbose_logger.propagate = True
|
4747e2f4
tangwang
embedding perform...
|
73
74
75
76
77
78
79
80
|
root_logger._embedding_logging_configured = True # type: ignore[attr-defined]
configure_embedding_logging()
logger = logging.getLogger(__name__)
verbose_logger = logging.getLogger("embedding.verbose")
|
0a3764c4
tangwang
优化embedding模型加载
|
81
|
# Models are loaded at startup, not lazily
|
950a640e
tangwang
embeddings
|
82
|
_text_model: Optional[Any] = None
|
c10f90fe
tangwang
cnclip
|
83
|
_image_model: Optional[ImageEncoderProtocol] = None
|
07cf5a93
tangwang
START_EMBEDDING=...
|
84
|
_text_backend_name: str = ""
|
7214c2e7
tangwang
mplemented**
|
85
86
87
88
89
90
91
92
93
|
_SERVICE_KIND = (os.getenv("EMBEDDING_SERVICE_KIND", "all") or "all").strip().lower()
if _SERVICE_KIND not in {"all", "text", "image"}:
raise RuntimeError(
f"Invalid EMBEDDING_SERVICE_KIND={_SERVICE_KIND!r}; expected all, text, or image"
)
_TEXT_ENABLED_BY_ENV = os.getenv("EMBEDDING_ENABLE_TEXT_MODEL", "true").lower() in ("1", "true", "yes")
_IMAGE_ENABLED_BY_ENV = os.getenv("EMBEDDING_ENABLE_IMAGE_MODEL", "true").lower() in ("1", "true", "yes")
open_text_model = _TEXT_ENABLED_BY_ENV and _SERVICE_KIND in {"all", "text"}
open_image_model = _IMAGE_ENABLED_BY_ENV and _SERVICE_KIND in {"all", "image"}
|
7bfb9946
tangwang
向量化模块
|
94
95
96
97
|
_text_encode_lock = threading.Lock()
_image_encode_lock = threading.Lock()
|
4747e2f4
tangwang
embedding perform...
|
98
99
100
101
102
103
104
|
_TEXT_MICROBATCH_WINDOW_SEC = max(
0.0, float(os.getenv("TEXT_MICROBATCH_WINDOW_MS", "4")) / 1000.0
)
_TEXT_REQUEST_TIMEOUT_SEC = max(
1.0, float(os.getenv("TEXT_REQUEST_TIMEOUT_SEC", "30"))
)
_TEXT_MAX_INFLIGHT = max(1, int(os.getenv("TEXT_MAX_INFLIGHT", "32")))
|
16204531
tangwang
docs
|
105
|
_IMAGE_MAX_INFLIGHT = max(1, int(os.getenv("IMAGE_MAX_INFLIGHT", "20")))
|
4747e2f4
tangwang
embedding perform...
|
106
107
108
109
110
|
_OVERLOAD_STATUS_CODE = int(os.getenv("EMBEDDING_OVERLOAD_STATUS_CODE", "503"))
_LOG_PREVIEW_COUNT = max(1, int(os.getenv("EMBEDDING_LOG_PREVIEW_COUNT", "3")))
_LOG_TEXT_PREVIEW_CHARS = max(32, int(os.getenv("EMBEDDING_LOG_TEXT_PREVIEW_CHARS", "120")))
_LOG_IMAGE_PREVIEW_CHARS = max(32, int(os.getenv("EMBEDDING_LOG_IMAGE_PREVIEW_CHARS", "180")))
_VECTOR_PREVIEW_DIMS = max(1, int(os.getenv("EMBEDDING_VECTOR_PREVIEW_DIMS", "6")))
|
7214c2e7
tangwang
mplemented**
|
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
|
_CACHE_PREFIX = str(REDIS_CONFIG.get("embedding_cache_prefix", "embedding")).strip() or "embedding"
@dataclass
class _EmbedResult:
vectors: List[Optional[List[float]]]
cache_hits: int
cache_misses: int
backend_elapsed_ms: float
mode: str
class _EndpointStats:
def __init__(self, name: str):
self.name = name
self._lock = threading.Lock()
self.request_total = 0
self.success_total = 0
self.failure_total = 0
self.rejected_total = 0
self.cache_hits = 0
self.cache_misses = 0
self.total_latency_ms = 0.0
self.total_backend_latency_ms = 0.0
def record_rejected(self) -> None:
with self._lock:
self.request_total += 1
self.rejected_total += 1
def record_completed(
self,
*,
success: bool,
latency_ms: float,
backend_latency_ms: float,
cache_hits: int,
cache_misses: int,
) -> None:
with self._lock:
self.request_total += 1
if success:
self.success_total += 1
else:
self.failure_total += 1
self.cache_hits += max(0, int(cache_hits))
self.cache_misses += max(0, int(cache_misses))
self.total_latency_ms += max(0.0, float(latency_ms))
self.total_backend_latency_ms += max(0.0, float(backend_latency_ms))
def snapshot(self) -> Dict[str, Any]:
with self._lock:
completed = self.success_total + self.failure_total
return {
"request_total": self.request_total,
"success_total": self.success_total,
"failure_total": self.failure_total,
"rejected_total": self.rejected_total,
"cache_hits": self.cache_hits,
"cache_misses": self.cache_misses,
"avg_latency_ms": round(self.total_latency_ms / completed, 3) if completed else 0.0,
"avg_backend_latency_ms": round(self.total_backend_latency_ms / completed, 3)
if completed
else 0.0,
}
|
4747e2f4
tangwang
embedding perform...
|
176
177
178
179
180
181
|
class _InflightLimiter:
def __init__(self, name: str, limit: int):
self.name = name
self.limit = max(1, int(limit))
|
4747e2f4
tangwang
embedding perform...
|
182
183
184
185
186
187
|
self._lock = threading.Lock()
self._active = 0
self._rejected = 0
self._completed = 0
self._failed = 0
self._max_active = 0
|
b754fd41
tangwang
图片向量化支持优先级参数
|
188
|
self._priority_bypass_total = 0
|
4747e2f4
tangwang
embedding perform...
|
189
|
|
b754fd41
tangwang
图片向量化支持优先级参数
|
190
191
192
|
def try_acquire(self, *, bypass_limit: bool = False) -> tuple[bool, int]:
with self._lock:
if not bypass_limit and self._active >= self.limit:
|
4747e2f4
tangwang
embedding perform...
|
193
194
|
self._rejected += 1
active = self._active
|
b754fd41
tangwang
图片向量化支持优先级参数
|
195
|
return False, active
|
4747e2f4
tangwang
embedding perform...
|
196
197
|
self._active += 1
self._max_active = max(self._max_active, self._active)
|
b754fd41
tangwang
图片向量化支持优先级参数
|
198
199
|
if bypass_limit:
self._priority_bypass_total += 1
|
4747e2f4
tangwang
embedding perform...
|
200
201
202
203
204
205
206
207
208
209
210
|
active = self._active
return True, active
def release(self, *, success: bool) -> int:
with self._lock:
self._active = max(0, self._active - 1)
if success:
self._completed += 1
else:
self._failed += 1
active = self._active
|
4747e2f4
tangwang
embedding perform...
|
211
212
213
214
215
216
217
218
219
220
221
|
return active
def snapshot(self) -> Dict[str, int]:
with self._lock:
return {
"limit": self.limit,
"active": self._active,
"rejected_total": self._rejected,
"completed_total": self._completed,
"failed_total": self._failed,
"max_active": self._max_active,
|
b754fd41
tangwang
图片向量化支持优先级参数
|
222
|
"priority_bypass_total": self._priority_bypass_total,
|
4747e2f4
tangwang
embedding perform...
|
223
224
225
|
}
|
b754fd41
tangwang
图片向量化支持优先级参数
|
226
227
228
229
230
231
232
233
234
235
236
237
238
|
def _effective_priority(priority: int) -> int:
return 1 if int(priority) > 0 else 0
def _priority_label(priority: int) -> str:
return "high" if _effective_priority(priority) > 0 else "normal"
@dataclass
class _TextDispatchTask:
normalized: List[str]
effective_normalize: bool
request_id: str
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
239
|
user_id: str
|
b754fd41
tangwang
图片向量化支持优先级参数
|
240
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
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
|
priority: int
created_at: float
done: threading.Event
result: Optional[_EmbedResult] = None
error: Optional[Exception] = None
_text_dispatch_high_queue: "deque[_TextDispatchTask]" = deque()
_text_dispatch_normal_queue: "deque[_TextDispatchTask]" = deque()
_text_dispatch_cv = threading.Condition()
_text_dispatch_workers: List[threading.Thread] = []
_text_dispatch_worker_stop = False
_text_dispatch_worker_count = 0
def _text_dispatch_queue_depth() -> Dict[str, int]:
with _text_dispatch_cv:
return {
"high": len(_text_dispatch_high_queue),
"normal": len(_text_dispatch_normal_queue),
"total": len(_text_dispatch_high_queue) + len(_text_dispatch_normal_queue),
}
def _pop_text_dispatch_task_locked() -> Optional["_TextDispatchTask"]:
if _text_dispatch_high_queue:
return _text_dispatch_high_queue.popleft()
if _text_dispatch_normal_queue:
return _text_dispatch_normal_queue.popleft()
return None
def _start_text_dispatch_workers() -> None:
global _text_dispatch_workers, _text_dispatch_worker_stop, _text_dispatch_worker_count
if _text_model is None:
return
target_worker_count = 1 if _text_backend_name == "local_st" else _TEXT_MAX_INFLIGHT
alive_workers = [worker for worker in _text_dispatch_workers if worker.is_alive()]
if len(alive_workers) == target_worker_count:
_text_dispatch_workers = alive_workers
_text_dispatch_worker_count = target_worker_count
return
_text_dispatch_worker_stop = False
_text_dispatch_worker_count = target_worker_count
_text_dispatch_workers = []
for idx in range(target_worker_count):
worker = threading.Thread(
target=_text_dispatch_worker_loop,
args=(idx,),
name=f"embed-text-dispatch-{idx}",
daemon=True,
)
worker.start()
_text_dispatch_workers.append(worker)
logger.info(
"Started text dispatch workers | backend=%s workers=%d",
_text_backend_name,
target_worker_count,
)
def _stop_text_dispatch_workers() -> None:
global _text_dispatch_worker_stop
with _text_dispatch_cv:
_text_dispatch_worker_stop = True
_text_dispatch_cv.notify_all()
def _text_dispatch_worker_loop(worker_idx: int) -> None:
while True:
with _text_dispatch_cv:
while (
not _text_dispatch_high_queue
and not _text_dispatch_normal_queue
and not _text_dispatch_worker_stop
):
_text_dispatch_cv.wait()
if _text_dispatch_worker_stop:
return
task = _pop_text_dispatch_task_locked()
if task is None:
continue
try:
queue_wait_ms = (time.perf_counter() - task.created_at) * 1000.0
logger.info(
"text dispatch start | worker=%d priority=%s inputs=%d queue_wait_ms=%.2f",
worker_idx,
_priority_label(task.priority),
len(task.normalized),
queue_wait_ms,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
330
|
extra=build_request_log_extra(task.request_id, task.user_id),
|
b754fd41
tangwang
图片向量化支持优先级参数
|
331
332
333
334
335
|
)
task.result = _embed_text_impl(
task.normalized,
task.effective_normalize,
task.request_id,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
336
|
task.user_id,
|
b754fd41
tangwang
图片向量化支持优先级参数
|
337
338
339
340
341
342
343
344
345
346
347
348
|
task.priority,
)
except Exception as exc:
task.error = exc
finally:
task.done.set()
def _submit_text_dispatch_and_wait(
normalized: List[str],
effective_normalize: bool,
request_id: str,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
349
|
user_id: str,
|
b754fd41
tangwang
图片向量化支持优先级参数
|
350
351
352
353
354
355
356
357
|
priority: int,
) -> _EmbedResult:
if not any(worker.is_alive() for worker in _text_dispatch_workers):
_start_text_dispatch_workers()
task = _TextDispatchTask(
normalized=normalized,
effective_normalize=effective_normalize,
request_id=request_id,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
358
|
user_id=user_id,
|
b754fd41
tangwang
图片向量化支持优先级参数
|
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
|
priority=_effective_priority(priority),
created_at=time.perf_counter(),
done=threading.Event(),
)
with _text_dispatch_cv:
if task.priority > 0:
_text_dispatch_high_queue.append(task)
else:
_text_dispatch_normal_queue.append(task)
_text_dispatch_cv.notify()
task.done.wait()
if task.error is not None:
raise task.error
if task.result is None:
raise RuntimeError("Text dispatch worker returned empty result")
return task.result
|
4747e2f4
tangwang
embedding perform...
|
377
378
|
_text_request_limiter = _InflightLimiter(name="text", limit=_TEXT_MAX_INFLIGHT)
_image_request_limiter = _InflightLimiter(name="image", limit=_IMAGE_MAX_INFLIGHT)
|
7214c2e7
tangwang
mplemented**
|
379
380
381
382
|
_text_stats = _EndpointStats(name="text")
_image_stats = _EndpointStats(name="image")
_text_cache = RedisEmbeddingCache(key_prefix=_CACHE_PREFIX, namespace="")
_image_cache = RedisEmbeddingCache(key_prefix=_CACHE_PREFIX, namespace="image")
|
7a013ca7
tangwang
多模态文本向量服务ok
|
383
|
_clip_text_cache = RedisEmbeddingCache(key_prefix=_CACHE_PREFIX, namespace="clip_text")
|
4747e2f4
tangwang
embedding perform...
|
384
|
|
7bfb9946
tangwang
向量化模块
|
385
|
|
efd435cf
tangwang
tei性能调优:
|
386
387
388
389
|
@dataclass
class _SingleTextTask:
text: str
normalize: bool
|
b754fd41
tangwang
图片向量化支持优先级参数
|
390
|
priority: int
|
efd435cf
tangwang
tei性能调优:
|
391
|
created_at: float
|
4747e2f4
tangwang
embedding perform...
|
392
|
request_id: str
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
393
|
user_id: str
|
efd435cf
tangwang
tei性能调优:
|
394
395
396
397
398
|
done: threading.Event
result: Optional[List[float]] = None
error: Optional[Exception] = None
|
b754fd41
tangwang
图片向量化支持优先级参数
|
399
400
|
_text_single_high_queue: "deque[_SingleTextTask]" = deque()
_text_single_normal_queue: "deque[_SingleTextTask]" = deque()
|
efd435cf
tangwang
tei性能调优:
|
401
402
403
|
_text_single_queue_cv = threading.Condition()
_text_batch_worker: Optional[threading.Thread] = None
_text_batch_worker_stop = False
|
28e57bb1
tangwang
日志体系优化
|
404
405
|
|
b754fd41
tangwang
图片向量化支持优先级参数
|
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
|
def _text_microbatch_queue_depth() -> Dict[str, int]:
with _text_single_queue_cv:
return {
"high": len(_text_single_high_queue),
"normal": len(_text_single_normal_queue),
"total": len(_text_single_high_queue) + len(_text_single_normal_queue),
}
def _pop_single_text_task_locked() -> Optional["_SingleTextTask"]:
if _text_single_high_queue:
return _text_single_high_queue.popleft()
if _text_single_normal_queue:
return _text_single_normal_queue.popleft()
return None
|
28e57bb1
tangwang
日志体系优化
|
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
|
def _compact_preview(text: str, max_chars: int) -> str:
compact = " ".join((text or "").split())
if len(compact) <= max_chars:
return compact
return compact[:max_chars] + "..."
def _preview_inputs(items: List[str], max_items: int, max_chars: int) -> List[Dict[str, Any]]:
previews: List[Dict[str, Any]] = []
for idx, item in enumerate(items[:max_items]):
previews.append(
{
"idx": idx,
"len": len(item),
"preview": _compact_preview(item, max_chars),
}
)
return previews
|
efd435cf
tangwang
tei性能调优:
|
441
442
|
|
4747e2f4
tangwang
embedding perform...
|
443
444
445
446
447
448
|
def _preview_vector(vec: Optional[List[float]], max_dims: int = _VECTOR_PREVIEW_DIMS) -> List[float]:
if not vec:
return []
return [round(float(v), 6) for v in vec[:max_dims]]
|
4747e2f4
tangwang
embedding perform...
|
449
450
451
452
453
454
455
|
def _resolve_request_id(http_request: Request) -> str:
header_value = http_request.headers.get("X-Request-ID")
if header_value and header_value.strip():
return header_value.strip()[:32]
return str(uuid.uuid4())[:8]
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
456
457
458
459
460
461
462
|
def _resolve_user_id(http_request: Request) -> str:
header_value = http_request.headers.get("X-User-ID") or http_request.headers.get("User-ID")
if header_value and header_value.strip():
return header_value.strip()[:64]
return "-1"
|
4747e2f4
tangwang
embedding perform...
|
463
464
465
466
467
468
|
def _request_client(http_request: Request) -> str:
client = getattr(http_request, "client", None)
host = getattr(client, "host", None)
return str(host or "-")
|
efd435cf
tangwang
tei性能调优:
|
469
470
|
def _encode_local_st(texts: List[str], normalize_embeddings: bool) -> Any:
with _text_encode_lock:
|
77516841
tangwang
tidy embeddings
|
471
|
return _text_model.encode(
|
efd435cf
tangwang
tei性能调优:
|
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
|
texts,
batch_size=int(CONFIG.TEXT_BATCH_SIZE),
device=CONFIG.TEXT_DEVICE,
normalize_embeddings=normalize_embeddings,
)
def _start_text_batch_worker() -> None:
global _text_batch_worker, _text_batch_worker_stop
if _text_batch_worker is not None and _text_batch_worker.is_alive():
return
_text_batch_worker_stop = False
_text_batch_worker = threading.Thread(
target=_text_batch_worker_loop,
name="embed-text-microbatch-worker",
daemon=True,
)
_text_batch_worker.start()
logger.info(
"Started local_st text micro-batch worker | window_ms=%.1f max_batch=%d",
_TEXT_MICROBATCH_WINDOW_SEC * 1000.0,
int(CONFIG.TEXT_BATCH_SIZE),
)
def _stop_text_batch_worker() -> None:
global _text_batch_worker_stop
with _text_single_queue_cv:
_text_batch_worker_stop = True
_text_single_queue_cv.notify_all()
def _text_batch_worker_loop() -> None:
max_batch = max(1, int(CONFIG.TEXT_BATCH_SIZE))
while True:
with _text_single_queue_cv:
|
b754fd41
tangwang
图片向量化支持优先级参数
|
508
509
510
511
512
|
while (
not _text_single_high_queue
and not _text_single_normal_queue
and not _text_batch_worker_stop
):
|
efd435cf
tangwang
tei性能调优:
|
513
514
515
516
|
_text_single_queue_cv.wait()
if _text_batch_worker_stop:
return
|
b754fd41
tangwang
图片向量化支持优先级参数
|
517
518
519
520
|
first_task = _pop_single_text_task_locked()
if first_task is None:
continue
batch: List[_SingleTextTask] = [first_task]
|
efd435cf
tangwang
tei性能调优:
|
521
522
523
524
525
526
|
deadline = time.perf_counter() + _TEXT_MICROBATCH_WINDOW_SEC
while len(batch) < max_batch:
remaining = deadline - time.perf_counter()
if remaining <= 0:
break
|
b754fd41
tangwang
图片向量化支持优先级参数
|
527
|
if not _text_single_high_queue and not _text_single_normal_queue:
|
efd435cf
tangwang
tei性能调优:
|
528
529
|
_text_single_queue_cv.wait(timeout=remaining)
continue
|
b754fd41
tangwang
图片向量化支持优先级参数
|
530
531
532
533
534
|
while len(batch) < max_batch:
next_task = _pop_single_text_task_locked()
if next_task is None:
break
batch.append(next_task)
|
efd435cf
tangwang
tei性能调优:
|
535
536
|
try:
|
4747e2f4
tangwang
embedding perform...
|
537
538
|
queue_wait_ms = [(time.perf_counter() - task.created_at) * 1000.0 for task in batch]
reqids = [task.request_id for task in batch]
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
539
|
uids = [task.user_id for task in batch]
|
4747e2f4
tangwang
embedding perform...
|
540
|
logger.info(
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
541
|
"text microbatch dispatch | size=%d priority=%s queue_wait_ms_min=%.2f queue_wait_ms_max=%.2f reqids=%s uids=%s preview=%s",
|
4747e2f4
tangwang
embedding perform...
|
542
|
len(batch),
|
b754fd41
tangwang
图片向量化支持优先级参数
|
543
|
_priority_label(max(task.priority for task in batch)),
|
4747e2f4
tangwang
embedding perform...
|
544
545
546
|
min(queue_wait_ms) if queue_wait_ms else 0.0,
max(queue_wait_ms) if queue_wait_ms else 0.0,
reqids,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
547
|
uids,
|
4747e2f4
tangwang
embedding perform...
|
548
549
550
551
552
|
_preview_inputs(
[task.text for task in batch],
_LOG_PREVIEW_COUNT,
_LOG_TEXT_PREVIEW_CHARS,
),
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
553
|
extra=build_request_log_extra(),
|
4747e2f4
tangwang
embedding perform...
|
554
555
|
)
batch_t0 = time.perf_counter()
|
efd435cf
tangwang
tei性能调优:
|
556
557
558
559
560
561
562
563
564
565
566
|
embs = _encode_local_st([task.text for task in batch], normalize_embeddings=False)
if embs is None or len(embs) != len(batch):
raise RuntimeError(
f"Text model response length mismatch in micro-batch: "
f"expected {len(batch)}, got {0 if embs is None else len(embs)}"
)
for task, emb in zip(batch, embs):
vec = _as_list(emb, normalize=task.normalize)
if vec is None:
raise RuntimeError("Text model returned empty embedding in micro-batch")
task.result = vec
|
4747e2f4
tangwang
embedding perform...
|
567
|
logger.info(
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
568
|
"text microbatch done | size=%d reqids=%s uids=%s dim=%d backend_elapsed_ms=%.2f",
|
4747e2f4
tangwang
embedding perform...
|
569
570
|
len(batch),
reqids,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
571
|
uids,
|
4747e2f4
tangwang
embedding perform...
|
572
573
|
len(batch[0].result) if batch and batch[0].result is not None else 0,
(time.perf_counter() - batch_t0) * 1000.0,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
574
|
extra=build_request_log_extra(),
|
4747e2f4
tangwang
embedding perform...
|
575
|
)
|
efd435cf
tangwang
tei性能调优:
|
576
|
except Exception as exc:
|
4747e2f4
tangwang
embedding perform...
|
577
|
logger.error(
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
578
|
"text microbatch failed | size=%d reqids=%s uids=%s error=%s",
|
4747e2f4
tangwang
embedding perform...
|
579
580
|
len(batch),
[task.request_id for task in batch],
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
581
|
[task.user_id for task in batch],
|
4747e2f4
tangwang
embedding perform...
|
582
583
|
exc,
exc_info=True,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
584
|
extra=build_request_log_extra(),
|
4747e2f4
tangwang
embedding perform...
|
585
|
)
|
efd435cf
tangwang
tei性能调优:
|
586
587
588
589
590
591
592
|
for task in batch:
task.error = exc
finally:
for task in batch:
task.done.set()
|
b754fd41
tangwang
图片向量化支持优先级参数
|
593
594
595
596
|
def _encode_single_text_with_microbatch(
text: str,
normalize: bool,
request_id: str,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
597
|
user_id: str,
|
b754fd41
tangwang
图片向量化支持优先级参数
|
598
599
|
priority: int,
) -> List[float]:
|
efd435cf
tangwang
tei性能调优:
|
600
601
602
|
task = _SingleTextTask(
text=text,
normalize=normalize,
|
b754fd41
tangwang
图片向量化支持优先级参数
|
603
|
priority=_effective_priority(priority),
|
efd435cf
tangwang
tei性能调优:
|
604
|
created_at=time.perf_counter(),
|
4747e2f4
tangwang
embedding perform...
|
605
|
request_id=request_id,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
606
|
user_id=user_id,
|
efd435cf
tangwang
tei性能调优:
|
607
608
609
|
done=threading.Event(),
)
with _text_single_queue_cv:
|
b754fd41
tangwang
图片向量化支持优先级参数
|
610
611
612
613
|
if task.priority > 0:
_text_single_high_queue.append(task)
else:
_text_single_normal_queue.append(task)
|
efd435cf
tangwang
tei性能调优:
|
614
615
616
617
|
_text_single_queue_cv.notify()
if not task.done.wait(timeout=_TEXT_REQUEST_TIMEOUT_SEC):
with _text_single_queue_cv:
|
b754fd41
tangwang
图片向量化支持优先级参数
|
618
|
queue = _text_single_high_queue if task.priority > 0 else _text_single_normal_queue
|
efd435cf
tangwang
tei性能调优:
|
619
|
try:
|
b754fd41
tangwang
图片向量化支持优先级参数
|
620
|
queue.remove(task)
|
efd435cf
tangwang
tei性能调优:
|
621
622
623
624
625
626
627
628
629
630
631
632
|
except ValueError:
pass
raise RuntimeError(
f"Timed out waiting for text micro-batch worker ({_TEXT_REQUEST_TIMEOUT_SEC:.1f}s)"
)
if task.error is not None:
raise task.error
if task.result is None:
raise RuntimeError("Text micro-batch worker returned empty result")
return task.result
|
0a3764c4
tangwang
优化embedding模型加载
|
633
634
635
|
@app.on_event("startup")
def load_models():
"""Load models at service startup to avoid first-request latency."""
|
07cf5a93
tangwang
START_EMBEDDING=...
|
636
|
global _text_model, _image_model, _text_backend_name
|
7bfb9946
tangwang
向量化模块
|
637
|
|
7214c2e7
tangwang
mplemented**
|
638
639
640
641
642
643
|
logger.info(
"Loading embedding models at startup | service_kind=%s text_enabled=%s image_enabled=%s",
_SERVICE_KIND,
open_text_model,
open_image_model,
)
|
7bfb9946
tangwang
向量化模块
|
644
|
|
40f1e391
tangwang
cnclip
|
645
646
|
if open_text_model:
try:
|
07cf5a93
tangwang
START_EMBEDDING=...
|
647
648
649
|
backend_name, backend_cfg = get_embedding_backend_config()
_text_backend_name = backend_name
if backend_name == "tei":
|
77516841
tangwang
tidy embeddings
|
650
|
from embeddings.text_embedding_tei import TEITextModel
|
07cf5a93
tangwang
START_EMBEDDING=...
|
651
|
|
86d8358b
tangwang
config optimize
|
652
653
|
base_url = backend_cfg.get("base_url") or CONFIG.TEI_BASE_URL
timeout_sec = int(backend_cfg.get("timeout_sec") or CONFIG.TEI_TIMEOUT_SEC)
|
07cf5a93
tangwang
START_EMBEDDING=...
|
654
655
656
657
|
logger.info("Loading text backend: tei (base_url=%s)", base_url)
_text_model = TEITextModel(
base_url=str(base_url),
timeout_sec=timeout_sec,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
658
659
660
|
max_client_batch_size=int(
backend_cfg.get("max_client_batch_size") or CONFIG.TEI_MAX_CLIENT_BATCH_SIZE
),
|
07cf5a93
tangwang
START_EMBEDDING=...
|
661
662
|
)
elif backend_name == "local_st":
|
77516841
tangwang
tidy embeddings
|
663
|
from embeddings.text_embedding_sentence_transformers import Qwen3TextModel
|
950a640e
tangwang
embeddings
|
664
|
|
86d8358b
tangwang
config optimize
|
665
|
model_id = backend_cfg.get("model_id") or CONFIG.TEXT_MODEL_ID
|
07cf5a93
tangwang
START_EMBEDDING=...
|
666
667
|
logger.info("Loading text backend: local_st (model=%s)", model_id)
_text_model = Qwen3TextModel(model_id=str(model_id))
|
efd435cf
tangwang
tei性能调优:
|
668
|
_start_text_batch_worker()
|
07cf5a93
tangwang
START_EMBEDDING=...
|
669
670
671
672
673
|
else:
raise ValueError(
f"Unsupported embedding backend: {backend_name}. "
"Supported: tei, local_st"
)
|
b754fd41
tangwang
图片向量化支持优先级参数
|
674
|
_start_text_dispatch_workers()
|
07cf5a93
tangwang
START_EMBEDDING=...
|
675
|
logger.info("Text backend loaded successfully: %s", _text_backend_name)
|
40f1e391
tangwang
cnclip
|
676
|
except Exception as e:
|
4747e2f4
tangwang
embedding perform...
|
677
|
logger.error("Failed to load text model: %s", e, exc_info=True)
|
40f1e391
tangwang
cnclip
|
678
|
raise
|
0a3764c4
tangwang
优化embedding模型加载
|
679
|
|
40f1e391
tangwang
cnclip
|
680
681
|
if open_image_model:
try:
|
c10f90fe
tangwang
cnclip
|
682
|
if CONFIG.USE_CLIP_AS_SERVICE:
|
950a640e
tangwang
embeddings
|
683
684
|
from embeddings.clip_as_service_encoder import ClipAsServiceImageEncoder
|
4747e2f4
tangwang
embedding perform...
|
685
686
687
688
689
|
logger.info(
"Loading image encoder via clip-as-service: %s (configured model: %s)",
CONFIG.CLIP_AS_SERVICE_SERVER,
CONFIG.CLIP_AS_SERVICE_MODEL_NAME,
)
|
c10f90fe
tangwang
cnclip
|
690
691
692
693
694
695
|
_image_model = ClipAsServiceImageEncoder(
server=CONFIG.CLIP_AS_SERVICE_SERVER,
batch_size=CONFIG.IMAGE_BATCH_SIZE,
)
logger.info("Image model (clip-as-service) loaded successfully")
else:
|
950a640e
tangwang
embeddings
|
696
697
|
from embeddings.clip_model import ClipImageModel
|
4747e2f4
tangwang
embedding perform...
|
698
699
700
701
702
|
logger.info(
"Loading local image model: %s (device: %s)",
CONFIG.IMAGE_MODEL_NAME,
CONFIG.IMAGE_DEVICE,
)
|
c10f90fe
tangwang
cnclip
|
703
704
705
706
707
|
_image_model = ClipImageModel(
model_name=CONFIG.IMAGE_MODEL_NAME,
device=CONFIG.IMAGE_DEVICE,
)
logger.info("Image model (local CN-CLIP) loaded successfully")
|
40f1e391
tangwang
cnclip
|
708
|
except Exception as e:
|
ed948666
tangwang
tidy
|
709
710
|
logger.error("Failed to load image model: %s", e, exc_info=True)
raise
|
0a3764c4
tangwang
优化embedding模型加载
|
711
712
|
logger.info("All embedding models loaded successfully, service ready")
|
7bfb9946
tangwang
向量化模块
|
713
714
|
|
efd435cf
tangwang
tei性能调优:
|
715
716
717
|
@app.on_event("shutdown")
def stop_workers() -> None:
_stop_text_batch_worker()
|
b754fd41
tangwang
图片向量化支持优先级参数
|
718
|
_stop_text_dispatch_workers()
|
efd435cf
tangwang
tei性能调优:
|
719
720
|
|
200fdddf
tangwang
embed norm
|
721
722
723
724
725
726
727
728
|
def _normalize_vector(vec: np.ndarray) -> np.ndarray:
norm = float(np.linalg.norm(vec))
if not np.isfinite(norm) or norm <= 0.0:
raise RuntimeError("Embedding vector has invalid norm (must be > 0)")
return vec / norm
def _as_list(embedding: Optional[np.ndarray], normalize: bool = False) -> Optional[List[float]]:
|
7bfb9946
tangwang
向量化模块
|
729
730
731
732
733
734
|
if embedding is None:
return None
if not isinstance(embedding, np.ndarray):
embedding = np.array(embedding, dtype=np.float32)
if embedding.ndim != 1:
embedding = embedding.reshape(-1)
|
200fdddf
tangwang
embed norm
|
735
736
737
738
|
embedding = embedding.astype(np.float32, copy=False)
if normalize:
embedding = _normalize_vector(embedding).astype(np.float32, copy=False)
return embedding.tolist()
|
7bfb9946
tangwang
向量化模块
|
739
740
|
|
7214c2e7
tangwang
mplemented**
|
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
|
def _try_full_text_cache_hit(
normalized: List[str],
effective_normalize: bool,
) -> Optional[_EmbedResult]:
out: List[Optional[List[float]]] = []
for text in normalized:
cached = _text_cache.get(build_text_cache_key(text, normalize=effective_normalize))
if cached is None:
return None
vec = _as_list(cached, normalize=False)
if vec is None:
return None
out.append(vec)
return _EmbedResult(
vectors=out,
cache_hits=len(out),
cache_misses=0,
backend_elapsed_ms=0.0,
mode="cache-only",
)
|
7a013ca7
tangwang
多模态文本向量服务ok
|
763
764
|
def _try_full_image_lane_cache_hit(
items: List[str],
|
7214c2e7
tangwang
mplemented**
|
765
|
effective_normalize: bool,
|
7a013ca7
tangwang
多模态文本向量服务ok
|
766
767
|
*,
lane: str,
|
7214c2e7
tangwang
mplemented**
|
768
769
|
) -> Optional[_EmbedResult]:
out: List[Optional[List[float]]] = []
|
7a013ca7
tangwang
多模态文本向量服务ok
|
770
771
|
for item in items:
if lane == "image":
|
5a01af3c
tangwang
多模态hashkey调整:1. 加...
|
772
773
774
|
ck = _mm_image_cache_key(
item, normalize=effective_normalize, model_name=CONFIG.MULTIMODAL_MODEL_NAME
)
|
7a013ca7
tangwang
多模态文本向量服务ok
|
775
776
|
cached = _image_cache.get(ck)
else:
|
5a01af3c
tangwang
多模态hashkey调整:1. 加...
|
777
778
779
|
ck = _mm_clip_text_cache_key(
item, normalize=effective_normalize, model_name=CONFIG.MULTIMODAL_MODEL_NAME
)
|
7a013ca7
tangwang
多模态文本向量服务ok
|
780
|
cached = _clip_text_cache.get(ck)
|
7214c2e7
tangwang
mplemented**
|
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
|
if cached is None:
return None
vec = _as_list(cached, normalize=False)
if vec is None:
return None
out.append(vec)
return _EmbedResult(
vectors=out,
cache_hits=len(out),
cache_misses=0,
backend_elapsed_ms=0.0,
mode="cache-only",
)
|
7a013ca7
tangwang
多模态文本向量服务ok
|
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
|
def _embed_image_lane_impl(
items: List[str],
effective_normalize: bool,
request_id: str,
user_id: str,
*,
lane: str,
) -> _EmbedResult:
if _image_model is None:
raise RuntimeError("Image model not loaded")
out: List[Optional[List[float]]] = [None] * len(items)
missing_indices: List[int] = []
missing_items: List[str] = []
missing_keys: List[str] = []
cache_hits = 0
for idx, item in enumerate(items):
if lane == "image":
|
5a01af3c
tangwang
多模态hashkey调整:1. 加...
|
814
815
816
|
ck = _mm_image_cache_key(
item, normalize=effective_normalize, model_name=CONFIG.MULTIMODAL_MODEL_NAME
)
|
7a013ca7
tangwang
多模态文本向量服务ok
|
817
818
|
cached = _image_cache.get(ck)
else:
|
5a01af3c
tangwang
多模态hashkey调整:1. 加...
|
819
820
821
|
ck = _mm_clip_text_cache_key(
item, normalize=effective_normalize, model_name=CONFIG.MULTIMODAL_MODEL_NAME
)
|
7a013ca7
tangwang
多模态文本向量服务ok
|
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
|
cached = _clip_text_cache.get(ck)
if cached is not None:
vec = _as_list(cached, normalize=False)
if vec is not None:
out[idx] = vec
cache_hits += 1
continue
missing_indices.append(idx)
missing_items.append(item)
missing_keys.append(ck)
if not missing_items:
logger.info(
"%s lane cache-only | inputs=%d normalize=%s dim=%d cache_hits=%d",
lane,
len(items),
effective_normalize,
len(out[0]) if out and out[0] is not None else 0,
cache_hits,
extra=build_request_log_extra(request_id=request_id, user_id=user_id),
)
return _EmbedResult(
vectors=out,
cache_hits=cache_hits,
cache_misses=0,
backend_elapsed_ms=0.0,
mode="cache-only",
)
backend_t0 = time.perf_counter()
|
b2dff38f
tangwang
embedding-image接口...
|
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
880
881
|
tmp_png_paths: List[str] = []
encode_inputs: List[str] = list(missing_items)
if lane == "image":
# Best-effort: rasterize SVGs into temporary PNGs so CN-CLIP can encode them.
for i, item in enumerate(missing_items):
if _looks_like_svg_image_ref(item):
png_path = _rasterize_svg_to_temp_png(item)
tmp_png_paths.append(png_path)
encode_inputs[i] = png_path
try:
with _image_encode_lock:
if lane == "image":
vectors = _image_model.encode_image_urls(
encode_inputs,
batch_size=CONFIG.IMAGE_BATCH_SIZE,
normalize_embeddings=effective_normalize,
)
else:
vectors = _image_model.encode_clip_texts(
missing_items,
batch_size=CONFIG.IMAGE_BATCH_SIZE,
normalize_embeddings=effective_normalize,
)
finally:
for p in tmp_png_paths:
try:
os.remove(p)
except Exception:
pass
|
7a013ca7
tangwang
多模态文本向量服务ok
|
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
|
if vectors is None or len(vectors) != len(missing_items):
raise RuntimeError(
f"{lane} lane length mismatch: expected {len(missing_items)}, "
f"got {0 if vectors is None else len(vectors)}"
)
for pos, ck, vec in zip(missing_indices, missing_keys, vectors):
out_vec = _as_list(vec, normalize=effective_normalize)
if out_vec is None:
raise RuntimeError(f"{lane} lane empty embedding at position {pos}")
out[pos] = out_vec
if lane == "image":
_image_cache.set(ck, np.asarray(out_vec, dtype=np.float32))
else:
_clip_text_cache.set(ck, np.asarray(out_vec, dtype=np.float32))
backend_elapsed_ms = (time.perf_counter() - backend_t0) * 1000.0
logger.info(
"%s lane backend-batch | inputs=%d normalize=%s dim=%d cache_hits=%d cache_misses=%d backend_elapsed_ms=%.2f",
lane,
len(items),
effective_normalize,
len(out[0]) if out and out[0] is not None else 0,
cache_hits,
len(missing_items),
backend_elapsed_ms,
extra=build_request_log_extra(request_id=request_id, user_id=user_id),
)
return _EmbedResult(
vectors=out,
cache_hits=cache_hits,
cache_misses=len(missing_items),
backend_elapsed_ms=backend_elapsed_ms,
mode="backend-batch",
)
|
7bfb9946
tangwang
向量化模块
|
919
920
|
@app.get("/health")
def health() -> Dict[str, Any]:
|
4747e2f4
tangwang
embedding perform...
|
921
|
"""Health check endpoint. Returns status and current throttling stats."""
|
7214c2e7
tangwang
mplemented**
|
922
|
ready = (not open_text_model or _text_model is not None) and (not open_image_model or _image_model is not None)
|
b754fd41
tangwang
图片向量化支持优先级参数
|
923
924
|
text_dispatch_depth = _text_dispatch_queue_depth()
text_microbatch_depth = _text_microbatch_queue_depth()
|
0a3764c4
tangwang
优化embedding模型加载
|
925
|
return {
|
7214c2e7
tangwang
mplemented**
|
926
927
|
"status": "ok" if ready else "degraded",
"service_kind": _SERVICE_KIND,
|
0a3764c4
tangwang
优化embedding模型加载
|
928
|
"text_model_loaded": _text_model is not None,
|
07cf5a93
tangwang
START_EMBEDDING=...
|
929
|
"text_backend": _text_backend_name,
|
0a3764c4
tangwang
优化embedding模型加载
|
930
|
"image_model_loaded": _image_model is not None,
|
7214c2e7
tangwang
mplemented**
|
931
932
933
|
"cache_enabled": {
"text": _text_cache.redis_client is not None,
"image": _image_cache.redis_client is not None,
|
7a013ca7
tangwang
多模态文本向量服务ok
|
934
|
"clip_text": _clip_text_cache.redis_client is not None,
|
7214c2e7
tangwang
mplemented**
|
935
|
},
|
4747e2f4
tangwang
embedding perform...
|
936
937
938
939
|
"limits": {
"text": _text_request_limiter.snapshot(),
"image": _image_request_limiter.snapshot(),
},
|
7214c2e7
tangwang
mplemented**
|
940
941
942
943
|
"stats": {
"text": _text_stats.snapshot(),
"image": _image_stats.snapshot(),
},
|
b754fd41
tangwang
图片向量化支持优先级参数
|
944
945
946
947
948
949
950
|
"text_dispatch": {
"workers": _text_dispatch_worker_count,
"workers_alive": sum(1 for worker in _text_dispatch_workers if worker.is_alive()),
"queue_depth": text_dispatch_depth["total"],
"queue_depth_high": text_dispatch_depth["high"],
"queue_depth_normal": text_dispatch_depth["normal"],
},
|
4747e2f4
tangwang
embedding perform...
|
951
952
|
"text_microbatch": {
"window_ms": round(_TEXT_MICROBATCH_WINDOW_SEC * 1000.0, 3),
|
b754fd41
tangwang
图片向量化支持优先级参数
|
953
954
955
|
"queue_depth": text_microbatch_depth["total"],
"queue_depth_high": text_microbatch_depth["high"],
"queue_depth_normal": text_microbatch_depth["normal"],
|
4747e2f4
tangwang
embedding perform...
|
956
957
958
|
"worker_alive": bool(_text_batch_worker is not None and _text_batch_worker.is_alive()),
"request_timeout_sec": _TEXT_REQUEST_TIMEOUT_SEC,
},
|
0a3764c4
tangwang
优化embedding模型加载
|
959
|
}
|
7bfb9946
tangwang
向量化模块
|
960
961
|
|
7214c2e7
tangwang
mplemented**
|
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
|
@app.get("/ready")
def ready() -> Dict[str, Any]:
text_ready = (not open_text_model) or (_text_model is not None)
image_ready = (not open_image_model) or (_image_model is not None)
if not (text_ready and image_ready):
raise HTTPException(
status_code=503,
detail={
"service_kind": _SERVICE_KIND,
"text_ready": text_ready,
"image_ready": image_ready,
},
)
return {
"status": "ready",
"service_kind": _SERVICE_KIND,
"text_ready": text_ready,
"image_ready": image_ready,
}
|
4747e2f4
tangwang
embedding perform...
|
983
984
985
986
|
def _embed_text_impl(
normalized: List[str],
effective_normalize: bool,
request_id: str,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
987
|
user_id: str,
|
b754fd41
tangwang
图片向量化支持优先级参数
|
988
|
priority: int = 0,
|
7214c2e7
tangwang
mplemented**
|
989
|
) -> _EmbedResult:
|
0a3764c4
tangwang
优化embedding模型加载
|
990
991
|
if _text_model is None:
raise RuntimeError("Text model not loaded")
|
28e57bb1
tangwang
日志体系优化
|
992
|
|
7214c2e7
tangwang
mplemented**
|
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
|
out: List[Optional[List[float]]] = [None] * len(normalized)
missing_indices: List[int] = []
missing_texts: List[str] = []
missing_cache_keys: List[str] = []
cache_hits = 0
for idx, text in enumerate(normalized):
cache_key = build_text_cache_key(text, normalize=effective_normalize)
cached = _text_cache.get(cache_key)
if cached is not None:
vec = _as_list(cached, normalize=False)
if vec is not None:
out[idx] = vec
cache_hits += 1
continue
missing_indices.append(idx)
missing_texts.append(text)
missing_cache_keys.append(cache_key)
if not missing_texts:
logger.info(
"text backend done | backend=%s mode=cache-only inputs=%d normalize=%s dim=%d cache_hits=%d cache_misses=0 backend_elapsed_ms=0.00",
_text_backend_name,
len(normalized),
effective_normalize,
len(out[0]) if out and out[0] is not None else 0,
cache_hits,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1019
|
extra=build_request_log_extra(request_id, user_id),
|
7214c2e7
tangwang
mplemented**
|
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
|
)
return _EmbedResult(
vectors=out,
cache_hits=cache_hits,
cache_misses=0,
backend_elapsed_ms=0.0,
mode="cache-only",
)
backend_t0 = time.perf_counter()
|
54ccf28c
tangwang
tei
|
1030
|
try:
|
efd435cf
tangwang
tei性能调优:
|
1031
|
if _text_backend_name == "local_st":
|
7214c2e7
tangwang
mplemented**
|
1032
1033
|
if len(missing_texts) == 1 and _text_batch_worker is not None:
computed = [
|
4747e2f4
tangwang
embedding perform...
|
1034
|
_encode_single_text_with_microbatch(
|
7214c2e7
tangwang
mplemented**
|
1035
|
missing_texts[0],
|
4747e2f4
tangwang
embedding perform...
|
1036
1037
|
normalize=effective_normalize,
request_id=request_id,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1038
|
user_id=user_id,
|
b754fd41
tangwang
图片向量化支持优先级参数
|
1039
|
priority=priority,
|
4747e2f4
tangwang
embedding perform...
|
1040
1041
|
)
]
|
7214c2e7
tangwang
mplemented**
|
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
|
mode = "microbatch-single"
else:
embs = _encode_local_st(missing_texts, normalize_embeddings=False)
computed = []
for i, emb in enumerate(embs):
vec = _as_list(emb, normalize=effective_normalize)
if vec is None:
raise RuntimeError(f"Text model returned empty embedding for missing index {i}")
computed.append(vec)
mode = "direct-batch"
|
efd435cf
tangwang
tei性能调优:
|
1052
|
else:
|
77516841
tangwang
tidy embeddings
|
1053
|
embs = _text_model.encode(
|
7214c2e7
tangwang
mplemented**
|
1054
|
missing_texts,
|
54ccf28c
tangwang
tei
|
1055
1056
|
batch_size=int(CONFIG.TEXT_BATCH_SIZE),
device=CONFIG.TEXT_DEVICE,
|
200fdddf
tangwang
embed norm
|
1057
|
normalize_embeddings=effective_normalize,
|
54ccf28c
tangwang
tei
|
1058
|
)
|
7214c2e7
tangwang
mplemented**
|
1059
1060
1061
1062
1063
1064
|
computed = []
for i, emb in enumerate(embs):
vec = _as_list(emb, normalize=False)
if vec is None:
raise RuntimeError(f"Text model returned empty embedding for missing index {i}")
computed.append(vec)
|
4747e2f4
tangwang
embedding perform...
|
1065
|
mode = "backend-batch"
|
54ccf28c
tangwang
tei
|
1066
|
except Exception as e:
|
4747e2f4
tangwang
embedding perform...
|
1067
1068
1069
1070
|
logger.error(
"Text embedding backend failure: %s",
e,
exc_info=True,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1071
|
extra=build_request_log_extra(request_id, user_id),
|
4747e2f4
tangwang
embedding perform...
|
1072
1073
1074
|
)
raise RuntimeError(f"Text embedding backend failure: {e}") from e
|
7214c2e7
tangwang
mplemented**
|
1075
|
if len(computed) != len(missing_texts):
|
ed948666
tangwang
tidy
|
1076
|
raise RuntimeError(
|
7214c2e7
tangwang
mplemented**
|
1077
1078
|
f"Text model response length mismatch: expected {len(missing_texts)}, "
f"got {len(computed)}"
|
ed948666
tangwang
tidy
|
1079
|
)
|
4747e2f4
tangwang
embedding perform...
|
1080
|
|
7214c2e7
tangwang
mplemented**
|
1081
1082
1083
1084
1085
|
for pos, cache_key, vec in zip(missing_indices, missing_cache_keys, computed):
out[pos] = vec
_text_cache.set(cache_key, np.asarray(vec, dtype=np.float32))
backend_elapsed_ms = (time.perf_counter() - backend_t0) * 1000.0
|
4747e2f4
tangwang
embedding perform...
|
1086
|
|
efd435cf
tangwang
tei性能调优:
|
1087
|
logger.info(
|
7214c2e7
tangwang
mplemented**
|
1088
|
"text backend done | backend=%s mode=%s inputs=%d normalize=%s dim=%d cache_hits=%d cache_misses=%d backend_elapsed_ms=%.2f",
|
efd435cf
tangwang
tei性能调优:
|
1089
|
_text_backend_name,
|
4747e2f4
tangwang
embedding perform...
|
1090
|
mode,
|
efd435cf
tangwang
tei性能调优:
|
1091
1092
|
len(normalized),
effective_normalize,
|
28e57bb1
tangwang
日志体系优化
|
1093
|
len(out[0]) if out and out[0] is not None else 0,
|
7214c2e7
tangwang
mplemented**
|
1094
1095
1096
|
cache_hits,
len(missing_texts),
backend_elapsed_ms,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1097
|
extra=build_request_log_extra(request_id, user_id),
|
efd435cf
tangwang
tei性能调优:
|
1098
|
)
|
7214c2e7
tangwang
mplemented**
|
1099
1100
1101
1102
1103
1104
1105
|
return _EmbedResult(
vectors=out,
cache_hits=cache_hits,
cache_misses=len(missing_texts),
backend_elapsed_ms=backend_elapsed_ms,
mode=mode,
)
|
7bfb9946
tangwang
向量化模块
|
1106
1107
|
|
4747e2f4
tangwang
embedding perform...
|
1108
1109
1110
1111
1112
1113
|
@app.post("/embed/text")
async def embed_text(
texts: List[str],
http_request: Request,
response: Response,
normalize: Optional[bool] = None,
|
b754fd41
tangwang
图片向量化支持优先级参数
|
1114
|
priority: int = 0,
|
4747e2f4
tangwang
embedding perform...
|
1115
|
) -> List[Optional[List[float]]]:
|
7214c2e7
tangwang
mplemented**
|
1116
1117
1118
|
if _text_model is None:
raise HTTPException(status_code=503, detail="Text embedding model not loaded in this service")
|
4747e2f4
tangwang
embedding perform...
|
1119
|
request_id = _resolve_request_id(http_request)
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1120
1121
|
user_id = _resolve_user_id(http_request)
_, _, log_tokens = bind_request_log_context(request_id, user_id)
|
4747e2f4
tangwang
embedding perform...
|
1122
|
response.headers["X-Request-ID"] = request_id
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1123
|
response.headers["X-User-ID"] = user_id
|
4747e2f4
tangwang
embedding perform...
|
1124
1125
|
request_started = time.perf_counter()
success = False
|
7214c2e7
tangwang
mplemented**
|
1126
1127
1128
|
backend_elapsed_ms = 0.0
cache_hits = 0
cache_misses = 0
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1129
1130
|
limiter_acquired = False
|
4747e2f4
tangwang
embedding perform...
|
1131
|
try:
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
|
if priority < 0:
raise HTTPException(status_code=400, detail="priority must be >= 0")
effective_priority = _effective_priority(priority)
effective_normalize = bool(CONFIG.TEXT_NORMALIZE_EMBEDDINGS) if normalize is None else bool(normalize)
normalized: List[str] = []
for i, t in enumerate(texts):
if not isinstance(t, str):
raise HTTPException(status_code=400, detail=f"Invalid text at index {i}: must be string")
s = t.strip()
if not s:
raise HTTPException(status_code=400, detail=f"Invalid text at index {i}: empty string")
normalized.append(s)
cache_check_started = time.perf_counter()
cache_only = _try_full_text_cache_hit(normalized, effective_normalize)
if cache_only is not None:
latency_ms = (time.perf_counter() - cache_check_started) * 1000.0
_text_stats.record_completed(
success=True,
latency_ms=latency_ms,
backend_latency_ms=0.0,
cache_hits=cache_only.cache_hits,
cache_misses=0,
)
logger.info(
"embed_text response | backend=%s mode=cache-only priority=%s inputs=%d normalize=%s dim=%d cache_hits=%d cache_misses=0 first_vector=%s latency_ms=%.2f",
_text_backend_name,
_priority_label(effective_priority),
len(normalized),
effective_normalize,
len(cache_only.vectors[0]) if cache_only.vectors and cache_only.vectors[0] is not None else 0,
cache_only.cache_hits,
_preview_vector(cache_only.vectors[0] if cache_only.vectors else None),
latency_ms,
extra=build_request_log_extra(request_id, user_id),
)
return cache_only.vectors
accepted, active = _text_request_limiter.try_acquire(bypass_limit=effective_priority > 0)
if not accepted:
_text_stats.record_rejected()
logger.warning(
"embed_text rejected | client=%s backend=%s priority=%s inputs=%d normalize=%s active=%d limit=%d preview=%s",
_request_client(http_request),
_text_backend_name,
_priority_label(effective_priority),
len(normalized),
effective_normalize,
active,
_TEXT_MAX_INFLIGHT,
_preview_inputs(normalized, _LOG_PREVIEW_COUNT, _LOG_TEXT_PREVIEW_CHARS),
extra=build_request_log_extra(request_id, user_id),
)
raise HTTPException(
status_code=_OVERLOAD_STATUS_CODE,
detail=(
"Text embedding service busy for priority=0 requests: "
f"active={active}, limit={_TEXT_MAX_INFLIGHT}"
),
)
limiter_acquired = True
|
4747e2f4
tangwang
embedding perform...
|
1193
|
logger.info(
|
b754fd41
tangwang
图片向量化支持优先级参数
|
1194
|
"embed_text request | client=%s backend=%s priority=%s inputs=%d normalize=%s active=%d limit=%d preview=%s",
|
4747e2f4
tangwang
embedding perform...
|
1195
1196
|
_request_client(http_request),
_text_backend_name,
|
b754fd41
tangwang
图片向量化支持优先级参数
|
1197
|
_priority_label(effective_priority),
|
4747e2f4
tangwang
embedding perform...
|
1198
1199
1200
1201
1202
|
len(normalized),
effective_normalize,
active,
_TEXT_MAX_INFLIGHT,
_preview_inputs(normalized, _LOG_PREVIEW_COUNT, _LOG_TEXT_PREVIEW_CHARS),
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1203
|
extra=build_request_log_extra(request_id, user_id),
|
4747e2f4
tangwang
embedding perform...
|
1204
1205
|
)
verbose_logger.info(
|
b754fd41
tangwang
图片向量化支持优先级参数
|
1206
|
"embed_text detail | payload=%s normalize=%s backend=%s priority=%s",
|
4747e2f4
tangwang
embedding perform...
|
1207
1208
1209
|
normalized,
effective_normalize,
_text_backend_name,
|
b754fd41
tangwang
图片向量化支持优先级参数
|
1210
|
_priority_label(effective_priority),
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1211
|
extra=build_request_log_extra(request_id, user_id),
|
4747e2f4
tangwang
embedding perform...
|
1212
|
)
|
b754fd41
tangwang
图片向量化支持优先级参数
|
1213
1214
1215
1216
1217
|
result = await run_in_threadpool(
_submit_text_dispatch_and_wait,
normalized,
effective_normalize,
request_id,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1218
|
user_id,
|
b754fd41
tangwang
图片向量化支持优先级参数
|
1219
1220
|
effective_priority,
)
|
4747e2f4
tangwang
embedding perform...
|
1221
|
success = True
|
7214c2e7
tangwang
mplemented**
|
1222
1223
1224
|
backend_elapsed_ms = result.backend_elapsed_ms
cache_hits = result.cache_hits
cache_misses = result.cache_misses
|
4747e2f4
tangwang
embedding perform...
|
1225
|
latency_ms = (time.perf_counter() - request_started) * 1000.0
|
7214c2e7
tangwang
mplemented**
|
1226
1227
1228
1229
1230
1231
1232
|
_text_stats.record_completed(
success=True,
latency_ms=latency_ms,
backend_latency_ms=backend_elapsed_ms,
cache_hits=cache_hits,
cache_misses=cache_misses,
)
|
4747e2f4
tangwang
embedding perform...
|
1233
|
logger.info(
|
b754fd41
tangwang
图片向量化支持优先级参数
|
1234
|
"embed_text response | backend=%s mode=%s priority=%s inputs=%d normalize=%s dim=%d cache_hits=%d cache_misses=%d first_vector=%s latency_ms=%.2f",
|
4747e2f4
tangwang
embedding perform...
|
1235
|
_text_backend_name,
|
7214c2e7
tangwang
mplemented**
|
1236
|
result.mode,
|
b754fd41
tangwang
图片向量化支持优先级参数
|
1237
|
_priority_label(effective_priority),
|
4747e2f4
tangwang
embedding perform...
|
1238
1239
|
len(normalized),
effective_normalize,
|
7214c2e7
tangwang
mplemented**
|
1240
1241
1242
1243
|
len(result.vectors[0]) if result.vectors and result.vectors[0] is not None else 0,
cache_hits,
cache_misses,
_preview_vector(result.vectors[0] if result.vectors else None),
|
4747e2f4
tangwang
embedding perform...
|
1244
|
latency_ms,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1245
|
extra=build_request_log_extra(request_id, user_id),
|
4747e2f4
tangwang
embedding perform...
|
1246
1247
|
)
verbose_logger.info(
|
b754fd41
tangwang
图片向量化支持优先级参数
|
1248
|
"embed_text result detail | count=%d priority=%s first_vector=%s latency_ms=%.2f",
|
7214c2e7
tangwang
mplemented**
|
1249
|
len(result.vectors),
|
b754fd41
tangwang
图片向量化支持优先级参数
|
1250
|
_priority_label(effective_priority),
|
7214c2e7
tangwang
mplemented**
|
1251
1252
1253
|
result.vectors[0][: _VECTOR_PREVIEW_DIMS]
if result.vectors and result.vectors[0] is not None
else [],
|
4747e2f4
tangwang
embedding perform...
|
1254
|
latency_ms,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1255
|
extra=build_request_log_extra(request_id, user_id),
|
4747e2f4
tangwang
embedding perform...
|
1256
|
)
|
7214c2e7
tangwang
mplemented**
|
1257
|
return result.vectors
|
4747e2f4
tangwang
embedding perform...
|
1258
1259
1260
1261
|
except HTTPException:
raise
except Exception as e:
latency_ms = (time.perf_counter() - request_started) * 1000.0
|
7214c2e7
tangwang
mplemented**
|
1262
1263
1264
1265
1266
1267
1268
|
_text_stats.record_completed(
success=False,
latency_ms=latency_ms,
backend_latency_ms=backend_elapsed_ms,
cache_hits=cache_hits,
cache_misses=cache_misses,
)
|
4747e2f4
tangwang
embedding perform...
|
1269
|
logger.error(
|
b754fd41
tangwang
图片向量化支持优先级参数
|
1270
|
"embed_text failed | backend=%s priority=%s inputs=%d normalize=%s latency_ms=%.2f error=%s",
|
4747e2f4
tangwang
embedding perform...
|
1271
|
_text_backend_name,
|
b754fd41
tangwang
图片向量化支持优先级参数
|
1272
|
_priority_label(effective_priority),
|
4747e2f4
tangwang
embedding perform...
|
1273
1274
1275
1276
1277
|
len(normalized),
effective_normalize,
latency_ms,
e,
exc_info=True,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1278
|
extra=build_request_log_extra(request_id, user_id),
|
4747e2f4
tangwang
embedding perform...
|
1279
1280
1281
|
)
raise HTTPException(status_code=502, detail=str(e)) from e
finally:
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
|
if limiter_acquired:
remaining = _text_request_limiter.release(success=success)
logger.info(
"embed_text finalize | success=%s priority=%s active_after=%d",
success,
_priority_label(effective_priority),
remaining,
extra=build_request_log_extra(request_id, user_id),
)
reset_request_log_context(log_tokens)
|
4747e2f4
tangwang
embedding perform...
|
1292
1293
|
|
7a013ca7
tangwang
多模态文本向量服务ok
|
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
|
def _parse_string_inputs(raw: List[Any], *, kind: str, empty_detail: str) -> List[str]:
out: List[str] = []
for i, x in enumerate(raw):
if not isinstance(x, str):
raise HTTPException(status_code=400, detail=f"Invalid {kind} at index {i}: must be string")
s = x.strip()
if not s:
raise HTTPException(status_code=400, detail=f"Invalid {kind} at index {i}: {empty_detail}")
out.append(s)
return out
|
4747e2f4
tangwang
embedding perform...
|
1304
|
|
4747e2f4
tangwang
embedding perform...
|
1305
|
|
b2dff38f
tangwang
embedding-image接口...
|
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
|
def _looks_like_svg_image_ref(value: str) -> bool:
"""
CN-CLIP image embedding path expects raster images (jpg/png/webp/...) that PIL can decode.
SVG is a vector format and currently not supported by the image embedding backend.
"""
v = (value or "").strip().lower()
if not v:
return False
# Drop query/fragment for URL suffix check.
for sep in ("?", "#"):
if sep in v:
v = v.split(sep, 1)[0]
return v.endswith(".svg") or v.startswith("data:image/svg+xml")
def _rasterize_svg_to_temp_png(svg_ref: str, *, timeout_sec: int = 10) -> str:
"""
Download/resolve an SVG ref (URL or local path) and rasterize it into a temporary PNG file.
Returns the PNG file path (caller is responsible for cleanup).
"""
if svg_ref.startswith(("http://", "https://")):
resp = requests.get(svg_ref, timeout=timeout_sec)
if resp.status_code != 200:
raise ValueError(f"HTTP {resp.status_code} when downloading SVG")
svg_bytes = resp.content
else:
with open(svg_ref, "rb") as f:
svg_bytes = f.read()
try:
import cairosvg # type: ignore
except Exception as exc: # pragma: no cover
raise RuntimeError(
"SVG rasterization requires optional dependency 'cairosvg'. "
"Install it in the embedding-image service environment."
) from exc
fd, out_path = tempfile.mkstemp(prefix="embed_svg_", suffix=".png")
os.close(fd)
try:
cairosvg.svg2png(bytestring=svg_bytes, write_to=out_path)
except Exception:
try:
os.remove(out_path)
except Exception:
pass
raise
return out_path
|
7a013ca7
tangwang
多模态文本向量服务ok
|
1357
1358
1359
1360
1361
|
async def _run_image_lane_embed(
*,
route: str,
lane: str,
items: List[str],
|
4747e2f4
tangwang
embedding perform...
|
1362
1363
|
http_request: Request,
response: Response,
|
7a013ca7
tangwang
多模态文本向量服务ok
|
1364
1365
1366
|
normalize: Optional[bool],
priority: int,
preview_chars: int,
|
4747e2f4
tangwang
embedding perform...
|
1367
|
) -> List[Optional[List[float]]]:
|
4747e2f4
tangwang
embedding perform...
|
1368
|
request_id = _resolve_request_id(http_request)
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1369
1370
|
user_id = _resolve_user_id(http_request)
_, _, log_tokens = bind_request_log_context(request_id, user_id)
|
4747e2f4
tangwang
embedding perform...
|
1371
|
response.headers["X-Request-ID"] = request_id
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1372
|
response.headers["X-User-ID"] = user_id
|
4747e2f4
tangwang
embedding perform...
|
1373
1374
|
request_started = time.perf_counter()
success = False
|
7214c2e7
tangwang
mplemented**
|
1375
1376
1377
|
backend_elapsed_ms = 0.0
cache_hits = 0
cache_misses = 0
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1378
|
limiter_acquired = False
|
7a013ca7
tangwang
多模态文本向量服务ok
|
1379
|
items_in: List[str] = list(items)
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1380
|
|
4747e2f4
tangwang
embedding perform...
|
1381
|
try:
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1382
1383
1384
|
if priority < 0:
raise HTTPException(status_code=400, detail="priority must be >= 0")
effective_priority = _effective_priority(priority)
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1385
|
effective_normalize = bool(CONFIG.IMAGE_NORMALIZE_EMBEDDINGS) if normalize is None else bool(normalize)
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1386
1387
|
cache_check_started = time.perf_counter()
|
7a013ca7
tangwang
多模态文本向量服务ok
|
1388
|
cache_only = _try_full_image_lane_cache_hit(items, effective_normalize, lane=lane)
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
|
if cache_only is not None:
latency_ms = (time.perf_counter() - cache_check_started) * 1000.0
_image_stats.record_completed(
success=True,
latency_ms=latency_ms,
backend_latency_ms=0.0,
cache_hits=cache_only.cache_hits,
cache_misses=0,
)
logger.info(
|
7a013ca7
tangwang
多模态文本向量服务ok
|
1399
1400
|
"%s response | mode=cache-only priority=%s inputs=%d normalize=%s dim=%d cache_hits=%d first_vector=%s latency_ms=%.2f",
route,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1401
|
_priority_label(effective_priority),
|
7a013ca7
tangwang
多模态文本向量服务ok
|
1402
|
len(items),
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
|
effective_normalize,
len(cache_only.vectors[0]) if cache_only.vectors and cache_only.vectors[0] is not None else 0,
cache_only.cache_hits,
_preview_vector(cache_only.vectors[0] if cache_only.vectors else None),
latency_ms,
extra=build_request_log_extra(request_id, user_id),
)
return cache_only.vectors
accepted, active = _image_request_limiter.try_acquire(bypass_limit=effective_priority > 0)
if not accepted:
_image_stats.record_rejected()
logger.warning(
|
7a013ca7
tangwang
多模态文本向量服务ok
|
1416
1417
|
"%s rejected | client=%s priority=%s inputs=%d normalize=%s active=%d limit=%d preview=%s",
route,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1418
1419
|
_request_client(http_request),
_priority_label(effective_priority),
|
7a013ca7
tangwang
多模态文本向量服务ok
|
1420
|
len(items),
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1421
1422
1423
|
effective_normalize,
active,
_IMAGE_MAX_INFLIGHT,
|
7a013ca7
tangwang
多模态文本向量服务ok
|
1424
|
_preview_inputs(items, _LOG_PREVIEW_COUNT, preview_chars),
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
|
extra=build_request_log_extra(request_id, user_id),
)
raise HTTPException(
status_code=_OVERLOAD_STATUS_CODE,
detail=(
"Image embedding service busy for priority=0 requests: "
f"active={active}, limit={_IMAGE_MAX_INFLIGHT}"
),
)
limiter_acquired = True
|
4747e2f4
tangwang
embedding perform...
|
1435
|
logger.info(
|
7a013ca7
tangwang
多模态文本向量服务ok
|
1436
1437
|
"%s request | client=%s priority=%s inputs=%d normalize=%s active=%d limit=%d preview=%s",
route,
|
4747e2f4
tangwang
embedding perform...
|
1438
|
_request_client(http_request),
|
b754fd41
tangwang
图片向量化支持优先级参数
|
1439
|
_priority_label(effective_priority),
|
7a013ca7
tangwang
多模态文本向量服务ok
|
1440
|
len(items),
|
4747e2f4
tangwang
embedding perform...
|
1441
1442
1443
|
effective_normalize,
active,
_IMAGE_MAX_INFLIGHT,
|
7a013ca7
tangwang
多模态文本向量服务ok
|
1444
|
_preview_inputs(items, _LOG_PREVIEW_COUNT, preview_chars),
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1445
|
extra=build_request_log_extra(request_id, user_id),
|
4747e2f4
tangwang
embedding perform...
|
1446
1447
|
)
verbose_logger.info(
|
7a013ca7
tangwang
多模态文本向量服务ok
|
1448
1449
1450
|
"%s detail | payload=%s normalize=%s priority=%s",
route,
items,
|
4747e2f4
tangwang
embedding perform...
|
1451
|
effective_normalize,
|
b754fd41
tangwang
图片向量化支持优先级参数
|
1452
|
_priority_label(effective_priority),
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1453
|
extra=build_request_log_extra(request_id, user_id),
|
4747e2f4
tangwang
embedding perform...
|
1454
|
)
|
7a013ca7
tangwang
多模态文本向量服务ok
|
1455
1456
1457
1458
1459
1460
1461
1462
|
result = await run_in_threadpool(
_embed_image_lane_impl,
items,
effective_normalize,
request_id,
user_id,
lane=lane,
)
|
4747e2f4
tangwang
embedding perform...
|
1463
|
success = True
|
7214c2e7
tangwang
mplemented**
|
1464
1465
1466
|
backend_elapsed_ms = result.backend_elapsed_ms
cache_hits = result.cache_hits
cache_misses = result.cache_misses
|
4747e2f4
tangwang
embedding perform...
|
1467
|
latency_ms = (time.perf_counter() - request_started) * 1000.0
|
7214c2e7
tangwang
mplemented**
|
1468
1469
1470
1471
1472
1473
1474
|
_image_stats.record_completed(
success=True,
latency_ms=latency_ms,
backend_latency_ms=backend_elapsed_ms,
cache_hits=cache_hits,
cache_misses=cache_misses,
)
|
4747e2f4
tangwang
embedding perform...
|
1475
|
logger.info(
|
7a013ca7
tangwang
多模态文本向量服务ok
|
1476
1477
|
"%s response | mode=%s priority=%s inputs=%d normalize=%s dim=%d cache_hits=%d cache_misses=%d first_vector=%s latency_ms=%.2f",
route,
|
7214c2e7
tangwang
mplemented**
|
1478
|
result.mode,
|
b754fd41
tangwang
图片向量化支持优先级参数
|
1479
|
_priority_label(effective_priority),
|
7a013ca7
tangwang
多模态文本向量服务ok
|
1480
|
len(items),
|
4747e2f4
tangwang
embedding perform...
|
1481
|
effective_normalize,
|
7214c2e7
tangwang
mplemented**
|
1482
1483
1484
1485
|
len(result.vectors[0]) if result.vectors and result.vectors[0] is not None else 0,
cache_hits,
cache_misses,
_preview_vector(result.vectors[0] if result.vectors else None),
|
4747e2f4
tangwang
embedding perform...
|
1486
|
latency_ms,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1487
|
extra=build_request_log_extra(request_id, user_id),
|
4747e2f4
tangwang
embedding perform...
|
1488
1489
|
)
verbose_logger.info(
|
7a013ca7
tangwang
多模态文本向量服务ok
|
1490
1491
|
"%s result detail | count=%d first_vector=%s latency_ms=%.2f",
route,
|
7214c2e7
tangwang
mplemented**
|
1492
1493
1494
1495
|
len(result.vectors),
result.vectors[0][: _VECTOR_PREVIEW_DIMS]
if result.vectors and result.vectors[0] is not None
else [],
|
4747e2f4
tangwang
embedding perform...
|
1496
|
latency_ms,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1497
|
extra=build_request_log_extra(request_id, user_id),
|
4747e2f4
tangwang
embedding perform...
|
1498
|
)
|
7214c2e7
tangwang
mplemented**
|
1499
|
return result.vectors
|
4747e2f4
tangwang
embedding perform...
|
1500
1501
1502
1503
|
except HTTPException:
raise
except Exception as e:
latency_ms = (time.perf_counter() - request_started) * 1000.0
|
7214c2e7
tangwang
mplemented**
|
1504
1505
1506
1507
1508
1509
1510
|
_image_stats.record_completed(
success=False,
latency_ms=latency_ms,
backend_latency_ms=backend_elapsed_ms,
cache_hits=cache_hits,
cache_misses=cache_misses,
)
|
4747e2f4
tangwang
embedding perform...
|
1511
|
logger.error(
|
7a013ca7
tangwang
多模态文本向量服务ok
|
1512
1513
|
"%s failed | priority=%s inputs=%d normalize=%s latency_ms=%.2f error=%s",
route,
|
b754fd41
tangwang
图片向量化支持优先级参数
|
1514
|
_priority_label(effective_priority),
|
7a013ca7
tangwang
多模态文本向量服务ok
|
1515
|
len(items_in),
|
4747e2f4
tangwang
embedding perform...
|
1516
1517
1518
1519
|
effective_normalize,
latency_ms,
e,
exc_info=True,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1520
|
extra=build_request_log_extra(request_id, user_id),
|
4747e2f4
tangwang
embedding perform...
|
1521
|
)
|
7a013ca7
tangwang
多模态文本向量服务ok
|
1522
|
raise HTTPException(status_code=502, detail=f"{route} backend failure: {e}") from e
|
4747e2f4
tangwang
embedding perform...
|
1523
|
finally:
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1524
1525
1526
|
if limiter_acquired:
remaining = _image_request_limiter.release(success=success)
logger.info(
|
7a013ca7
tangwang
多模态文本向量服务ok
|
1527
1528
|
"%s finalize | success=%s priority=%s active_after=%d",
route,
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
1529
1530
1531
1532
1533
1534
|
success,
_priority_label(effective_priority),
remaining,
extra=build_request_log_extra(request_id, user_id),
)
reset_request_log_context(log_tokens)
|
7a013ca7
tangwang
多模态文本向量服务ok
|
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
|
@app.post("/embed/image")
async def embed_image(
images: List[str],
http_request: Request,
response: Response,
normalize: Optional[bool] = None,
priority: int = 0,
) -> List[Optional[List[float]]]:
if _image_model is None:
raise HTTPException(status_code=503, detail="Image embedding model not loaded in this service")
items = _parse_string_inputs(images, kind="image", empty_detail="empty URL/path")
return await _run_image_lane_embed(
route="embed_image",
lane="image",
items=items,
http_request=http_request,
response=response,
normalize=normalize,
priority=priority,
preview_chars=_LOG_IMAGE_PREVIEW_CHARS,
)
@app.post("/embed/clip_text")
async def embed_clip_text(
texts: List[str],
http_request: Request,
response: Response,
normalize: Optional[bool] = None,
priority: int = 0,
) -> List[Optional[List[float]]]:
"""CN-CLIP 文本塔,与 ``POST /embed/image`` 同向量空间。"""
if _image_model is None:
raise HTTPException(status_code=503, detail="Image embedding model not loaded in this service")
items = _parse_string_inputs(texts, kind="text", empty_detail="empty string")
return await _run_image_lane_embed(
route="embed_clip_text",
lane="clip_text",
items=items,
http_request=http_request,
response=response,
normalize=normalize,
priority=priority,
preview_chars=_LOG_TEXT_PREVIEW_CHARS,
)
|
5a01af3c
tangwang
多模态hashkey调整:1. 加...
|
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
|
def build_image_cache_key(url: str, *, normalize: bool, model_name: Optional[str] = None) -> str:
"""Tests/tools: same key as ``/embed/image`` lane; defaults to ``CONFIG.MULTIMODAL_MODEL_NAME``."""
return _mm_image_cache_key(
url, normalize=normalize, model_name=model_name or CONFIG.MULTIMODAL_MODEL_NAME
)
def build_clip_text_cache_key(text: str, *, normalize: bool, model_name: Optional[str] = None) -> str:
"""Tests/tools: same key as ``/embed/clip_text`` lane; defaults to ``CONFIG.MULTIMODAL_MODEL_NAME``."""
return _mm_clip_text_cache_key(
text, normalize=normalize, model_name=model_name or CONFIG.MULTIMODAL_MODEL_NAME
)
|