File size: 22,511 Bytes
f687b59
a6b29f5
f687b59
 
 
 
a6b29f5
 
 
 
 
 
 
 
 
 
 
 
 
 
f687b59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f8bd1db
 
 
 
 
 
 
 
 
 
 
f687b59
 
 
 
 
 
 
 
 
 
 
 
 
 
f8bd1db
 
 
 
f687b59
f8bd1db
 
f687b59
 
 
43d9977
 
 
f687b59
 
 
 
 
 
43d9977
 
 
 
 
 
 
 
 
 
 
 
f687b59
 
 
 
 
 
4f0f497
 
f687b59
 
43d9977
 
 
4f0f497
f687b59
4f0f497
f687b59
 
 
 
 
 
43d9977
 
f687b59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f0f497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f687b59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43d9977
 
 
 
 
 
 
f687b59
43d9977
f687b59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43d9977
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f687b59
 
 
 
 
 
 
 
 
43d9977
f687b59
 
 
 
 
 
43d9977
f687b59
 
 
43d9977
 
 
 
 
 
 
 
 
 
 
 
 
 
f687b59
 
 
43d9977
 
 
 
 
 
f687b59
 
 
43d9977
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f687b59
 
 
 
 
 
 
43d9977
 
f687b59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43d9977
 
 
 
f687b59
 
 
4f0f497
a6b29f5
f687b59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43d9977
 
 
 
 
 
 
 
 
f687b59
43d9977
 
 
 
 
 
 
 
 
 
 
 
 
f687b59
 
 
 
 
 
 
 
 
 
43d9977
 
 
 
 
 
 
f687b59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
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
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
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
import os
import platform
import time
from pathlib import Path
from typing import Dict, List, Optional, Union


# ==================== CPU 探测(判断 HF 宿主是否 Intel)====================
def _detect_cpu() -> str:
    """返回 CPU 型号名,用于判断 HF Space 宿主是 Intel/AMD/ARM。"""
    try:
        # Linux 容器最可靠:/proc/cpuinfo 首个 model name
        with open("/proc/cpuinfo", "r", encoding="utf-8", errors="ignore") as f:
            for line in f:
                if line.lower().startswith("model name"):
                    return line.split(":", 1)[1].strip()
    except OSError:
        pass
    return platform.processor() or platform.machine() or "unknown"

# ==================== 项目路径 ====================
PROJECT_ROOT = Path(__file__).resolve().parent

os.environ.setdefault("HF_HOME", str(PROJECT_ROOT / "hf_cache"))
os.environ.setdefault("TRANSFORMERS_CACHE", os.environ["HF_HOME"])
os.environ.setdefault("HUGGINGFACE_HUB_CACHE", str(Path(os.environ["HF_HOME"]) / "hub"))
os.environ.setdefault("UV_CACHE_DIR", str(PROJECT_ROOT / "uv_cache"))

# 控制线程,避免无故占满内存/CPU(可按机器核心数微调)
os.environ.setdefault("OMP_NUM_THREADS", "4")
os.environ.setdefault("OPENBLAS_NUM_THREADS", "4")
os.environ.setdefault("MKL_NUM_THREADS", "4")
os.environ.setdefault("NUMEXPR_NUM_THREADS", "4")

# ==================== 业务配置 ====================
# pooling: mean = BGE 系;last_token = Qwen3-Embedding 系
# padding_side: Qwen3 官方要求 left
AVAILABLE_MODELS = {
    # 默认:中文快、HF CPU 友好(约 0.1B)
    "bge-base-zh-v1.5": {
        "id": "BAAI/bge-base-zh-v1.5",
        "path": PROJECT_ROOT / "models" / "bge-base-zh-v1.5",
        "dim": 768,
        "desc": "Chinese base embedding (fast, quality/speed balanced)",
        "pooling": "mean",
        "padding_side": "right",
        "default_instruction": None,
    },
    # 质量优先:多语/中文更强,明显更慢、更大
    "qwen3-embedding-0.6b": {
        "id": "Qwen/Qwen3-Embedding-0.6B",
        "path": PROJECT_ROOT / "models" / "qwen3-embedding-0.6b",
        "dim": 1024,
        "desc": "Qwen3 Embedding 0.6B (multilingual/Chinese strong, OpenVINO)",
        "pooling": "last_token",
        "padding_side": "left",
        # 检索 query 建议带 instruct;文档侧可传 instruction="" 覆盖为不用
        "default_instruction": (
            "Given a web search query, retrieve relevant passages that answer the query"
        ),
    },
}

# 切换模型:环境变量 DEFAULT_MODEL=qwen3-embedding-0.6b 或 bge-base-zh-v1.5
# 也可请求体 "model": "qwen3-embedding-0.6b"
_DEFAULT_FALLBACK = "bge-base-zh-v1.5"
DEFAULT_MODEL_KEY = os.environ.get("DEFAULT_MODEL", _DEFAULT_FALLBACK).strip()
if DEFAULT_MODEL_KEY not in AVAILABLE_MODELS:
    print(f"[warn] unknown DEFAULT_MODEL={DEFAULT_MODEL_KEY!r}, fallback {_DEFAULT_FALLBACK}")
    DEFAULT_MODEL_KEY = _DEFAULT_FALLBACK

# 性能设备:本地可 NPU;HF Spaces / 无 NPU 时自动回退 CPU
DEVICE = os.environ.get("DEVICE", "NPU").upper()  # NPU | CPU | AUTO
# 序列长度上限(truncate);CPU 默认动态 pad 到 batch 内最长,不再强制 pad 满
# 建议:HF 免费 CPU 512;本机 1024;再大延迟/内存线性涨
MAX_LENGTH = int(os.environ.get("MAX_LENGTH", "512"))
NPU_BATCH = 1
PORT = int(os.environ.get("PORT", "8000"))

# True=启动更轻,首请求稍慢;False=启动即加载,首请求更快
LAZY_LOAD = os.environ.get("LAZY_LOAD", "0").lower() in ("1", "true", "yes")

# CPU 单次推理条数(ReadAny 远程默认 batch=8;HF 2 核建议 2)
CPU_MAX_BATCH = int(os.environ.get("CPU_MAX_BATCH", "2"))
# 单请求最多条数(防止整本书一次塞进来)
MAX_INPUTS_PER_REQUEST = int(os.environ.get("MAX_INPUTS_PER_REQUEST", "32"))
# 单条字符上限(ReadAny 侧已截 1800;服务端再兜底)
MAX_CHARS_PER_INPUT = int(os.environ.get("MAX_CHARS_PER_INPUT", "4000"))
# CPU 是否强制 pad 到 MAX_LENGTH(NPU 始终固定;HF 请保持 false)
FORCE_STATIC_PAD = os.environ.get("FORCE_STATIC_PAD", "0").lower() in (
    "1",
    "true",
    "yes",
)
# 是否在未显式传 instruction 时使用模型 default_instruction
USE_DEFAULT_INSTRUCTION = os.environ.get("USE_DEFAULT_INSTRUCTION", "1").lower() in (
    "1",
    "true",
    "yes",
)
# 调用密钥:HF Space 用 Secrets 配置 API_KEY;未设置则不鉴权(方便本机调试)
API_KEY = (os.environ.get("API_KEY") or os.environ.get("EMBEDDING_API_KEY") or "").strip()
# ==================================================

import logging
import traceback

from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
import uvicorn
import numpy as np
from openvino import Core
from transformers import AutoTokenizer

logger = logging.getLogger("ov_embedding")

app = FastAPI(
    title="OpenVINO Lite Embedding",
    version="3.2-qwen",
    docs_url="/docs",
    redoc_url=None,
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 鉴权放行:探活/根路径;设置了 API_KEY 后保护 /v1/* 与 /docs
_AUTH_PUBLIC_PATHS = frozenset({"/", "/health"})


def _extract_api_key(request: Request) -> str:
    """支持 Authorization: Bearer <key> 或 X-API-Key: <key>。"""
    auth = request.headers.get("authorization") or request.headers.get("Authorization") or ""
    if auth.lower().startswith("bearer "):
        return auth[7:].strip()
    return (request.headers.get("x-api-key") or request.headers.get("X-API-Key") or "").strip()


@app.middleware("http")
async def api_key_middleware(request: Request, call_next):
    if not API_KEY:
        return await call_next(request)
    path = request.url.path.rstrip("/") or "/"
    if path in _AUTH_PUBLIC_PATHS or request.method == "OPTIONS":
        return await call_next(request)
    if _extract_api_key(request) != API_KEY:
        return JSONResponse(
            status_code=401,
            content={"detail": "Invalid or missing API key. Use Authorization: Bearer <API_KEY> or X-API-Key."},
        )
    return await call_next(request)

core = Core()
models_cache: Dict[str, dict] = {}


def mean_pooling(last_hidden: np.ndarray, attention_mask: np.ndarray) -> np.ndarray:
    """BGE-style mean pooling. last_hidden: [B,S,H], mask: [B,S]"""
    mask = np.expand_dims(attention_mask.astype(np.float32), axis=-1)
    summed = np.sum(last_hidden * mask, axis=1)
    counts = np.clip(mask.sum(axis=1), a_min=1e-9, a_max=None)
    return summed / counts


def last_token_pool(last_hidden: np.ndarray, attention_mask: np.ndarray) -> np.ndarray:
    """Qwen3-Embedding 官方 last-token pooling. last_hidden: [B,S,H], mask: [B,S]"""
    # left padding 时有效 token 在右侧,取最后一列即可
    if int(attention_mask[:, -1].sum()) == attention_mask.shape[0]:
        return last_hidden[:, -1]
    seq_lens = attention_mask.sum(axis=1).astype(np.int64) - 1
    batch = np.arange(last_hidden.shape[0])
    return last_hidden[batch, seq_lens]


def l2_normalize(x: np.ndarray, eps: float = 1e-12) -> np.ndarray:
    norm = np.linalg.norm(x, axis=-1, keepdims=True)
    return x / np.clip(norm, a_min=eps, a_max=None)


def find_ir_xml(model_path: Path) -> Path:
    for name in ("openvino_model.xml", "model.xml"):
        p = model_path / name
        if p.exists():
            return p
    xmls = sorted(model_path.glob("*.xml"))
    if not xmls:
        raise FileNotFoundError(f"No OpenVINO IR (.xml) under {model_path}")
    return xmls[0]


def export_ir_once(model_key: str) -> None:
    """Only when local IR missing. Uses optimum once (heavier import)."""
    cfg = AVAILABLE_MODELS[model_key]
    model_path = cfg["path"]
    model_id = cfg["id"]
    model_path.mkdir(parents=True, exist_ok=True)

    if any(model_path.glob("*.xml")):
        return

    print(f"[export] IR missing, exporting once: {model_id}")
    from optimum.intel import OVModelForFeatureExtraction

    # 优先 INT8 降内存(HF 免费 16GB / 本机也更轻);失败再 FP16/FP32
    ov_model = None
    last_err = None
    for label, kwargs in (
        (
            "int8",
            {
                "export": True,
                "device": "CPU",
                "compile": False,
                "trust_remote_code": True,
                "quantization_config": {"bits": 8},
            },
        ),
        (
            "fp16/default",
            {
                "export": True,
                "device": "CPU",
                "compile": False,
                "trust_remote_code": True,
            },
        ),
    ):
        try:
            print(f"[export] try {label} ...")
            # quantization_config 若为 dict,改用 OVWeightQuantizationConfig
            kw = dict(kwargs)
            qcfg = kw.get("quantization_config")
            if isinstance(qcfg, dict):
                try:
                    from optimum.intel import OVWeightQuantizationConfig

                    kw["quantization_config"] = OVWeightQuantizationConfig(**qcfg)
                except Exception as e:
                    print(f"[export] skip int8 config: {e}")
                    continue
            ov_model = OVModelForFeatureExtraction.from_pretrained(model_id, **kw)
            print(f"[export] ok with {label}")
            break
        except Exception as e:
            last_err = e
            print(f"[export] fail {label}: {e}")
            ov_model = None

    if ov_model is None:
        raise RuntimeError(f"export failed: {last_err}")

    tok = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
    ov_model.save_pretrained(str(model_path))
    tok.save_pretrained(str(model_path))
    print(f"[export] saved: {model_path}")


def reshape_static(model, batch: int, seq: int) -> None:
    """Remove dynamic -1 dims for NPU."""
    shape_map = {}
    for inp in model.inputs:
        ps = inp.get_partial_shape()
        new_dims = []
        changed = False
        for i, d in enumerate(ps):
            if d.is_dynamic:
                new_dims.append(batch if i == 0 else seq)
                changed = True
            else:
                new_dims.append(int(d.get_length()))
        if changed:
            shape_map[inp] = new_dims
    if shape_map:
        model.reshape(shape_map)


def compile_ir(xml_path: Path, prefer: str):
    prefer = prefer.upper()
    order = []
    if prefer == "NPU":
        order = ["NPU", "CPU"]
    elif prefer == "AUTO":
        order = ["AUTO", "CPU"]
    else:
        order = ["CPU"]

    last_err = None
    for dev in order:
        try:
            m = core.read_model(str(xml_path))
            # NPU 必须静态 shape;CPU 默认保留动态,配合动态 pad 省内存
            if dev == "NPU" or FORCE_STATIC_PAD:
                try:
                    b = NPU_BATCH if dev == "NPU" else 1
                    reshape_static(m, b, MAX_LENGTH)
                except Exception as e:
                    print(f"[warn] reshape on {dev}: {e}")
            compiled = core.compile_model(m, dev)
            print(f"[compile] OK on {dev} static_pad={dev == 'NPU' or FORCE_STATIC_PAD}")
            return compiled, dev
        except Exception as e:
            last_err = e
            print(f"[compile] fail on {dev}: {e}")

    raise RuntimeError(f"compile failed: {last_err}")


def load_model(model_key: str):
    if model_key in models_cache:
        return models_cache[model_key]
    if model_key not in AVAILABLE_MODELS:
        raise ValueError(f"unsupported model: {model_key}")

    cfg = AVAILABLE_MODELS[model_key]
    model_path = cfg["path"]
    print(f"[load] {model_key}")

    export_ir_once(model_key)
    xml_path = find_ir_xml(model_path)
    tokenizer = AutoTokenizer.from_pretrained(
        str(model_path),
        use_fast=True,
        trust_remote_code=True,
    )
    pad_side = cfg.get("padding_side") or "right"
    tokenizer.padding_side = pad_side

    compiled, actual_device = compile_ir(xml_path, DEVICE)

    input_names = []
    for inp in compiled.inputs:
        input_names.append(inp.get_any_name())

    models_cache[model_key] = {
        "compiled": compiled,
        "tokenizer": tokenizer,
        "dim": cfg["dim"],
        "id": cfg["id"],
        "actual_device": actual_device,
        "input_names": input_names,
        "output": compiled.outputs[0],
        "static_single": actual_device == "NPU",
        "pooling": cfg.get("pooling", "mean"),
        "default_instruction": cfg.get("default_instruction"),
        "padding_side": pad_side,
    }
    print(f"[ready] {model_key} device={actual_device} pooling={cfg.get('pooling')}")
    return models_cache[model_key]


def _feed_dict(data: dict, encoded: dict) -> dict:
    feed = {}
    for name in data["input_names"]:
        key = name.split(":")[0]
        if key in encoded:
            feed[name] = encoded[key]
        elif key == "token_type_ids":
            feed[name] = np.zeros_like(encoded["input_ids"])
        elif name in encoded:
            feed[name] = encoded[name]
    return feed


def _pool(data: dict, out: np.ndarray, attention_mask: np.ndarray) -> np.ndarray:
    if out.ndim == 2:
        return out
    if data["pooling"] == "last_token":
        return last_token_pool(out, attention_mask)
    return mean_pooling(out, attention_mask)


def resolve_instruction(model_key: str, instruction: Optional[str]) -> Optional[str]:
    """
    instruction 语义:
    - 请求未传(None)且 USE_DEFAULT_INSTRUCTION:用模型 default_instruction
    - 请求传 "":强制不用 instruct(文档索引)
    - 请求传非空:自定义 task instruct
    """
    cfg = AVAILABLE_MODELS[model_key]
    if instruction is not None:
        return instruction.strip() or None
    if USE_DEFAULT_INSTRUCTION:
        return cfg.get("default_instruction") or None
    return None


def apply_instruction(texts: List[str], instruction: Optional[str]) -> List[str]:
    if not instruction:
        return texts
    out = []
    for t in texts:
        if t.startswith("Instruct:"):
            out.append(t)
        else:
            out.append(f"Instruct: {instruction}\nQuery:{t}")
    return out


def _tokenize_batch(
    tokenizer,
    texts: List[str],
    *,
    static_pad: bool,
) -> dict:
    """截断到 MAX_LENGTH;CPU 默认动态 pad,降低激活内存。"""
    if static_pad or FORCE_STATIC_PAD:
        return tokenizer(
            texts,
            padding="max_length",
            truncation=True,
            max_length=MAX_LENGTH,
            return_tensors="np",
        )
    return tokenizer(
        texts,
        padding=True,
        truncation=True,
        max_length=MAX_LENGTH,
        return_tensors="np",
    )


def infer_batch(data: dict, texts: List[str]) -> np.ndarray:
    """Return [B, H] float32 normalized embeddings."""
    tokenizer = data["tokenizer"]
    compiled = data["compiled"]

    # NPU: fixed [1, MAX_LENGTH]
    if data["static_single"]:
        out_list = []
        for t in texts:
            enc = _tokenize_batch(tokenizer, [t], static_pad=True)
            result = compiled(_feed_dict(data, enc))
            out = np.array(result[data["output"]])
            emb = _pool(data, out, enc["attention_mask"])
            out_list.append(l2_normalize(emb)[0])
        return np.stack(out_list, axis=0)

    # CPU/AUTO: 小批量 + 动态 pad(适配 ReadAny batch=8)
    all_emb = []
    for i in range(0, len(texts), CPU_MAX_BATCH):
        chunk = texts[i : i + CPU_MAX_BATCH]
        enc = _tokenize_batch(tokenizer, chunk, static_pad=False)
        seq_len = int(enc["input_ids"].shape[1])
        t0 = time.time()
        try:
            result = compiled(_feed_dict(data, enc))
        except Exception as e:
            logger.error(
                "infer fail batch=%s seq=%s chars=%s err=%s",
                len(chunk),
                seq_len,
                [len(x) for x in chunk],
                e,
            )
            raise
        out = np.array(result[data["output"]])
        emb = _pool(data, out, enc["attention_mask"])
        all_emb.append(l2_normalize(emb))
        logger.info(
            "infer ok n=%s seq=%s ms=%.0f",
            len(chunk),
            seq_len,
            (time.time() - t0) * 1000,
        )
    return np.concatenate(all_emb, axis=0)


def sanitize_texts(texts: List[str]) -> List[str]:
    cleaned: List[str] = []
    for t in texts:
        if not isinstance(t, str):
            t = str(t)
        # 空串用占位,避免 tokenizer/模型异常
        t = t.strip() if t else ""
        if not t:
            t = " "
        if len(t) > MAX_CHARS_PER_INPUT:
            t = t[:MAX_CHARS_PER_INPUT]
        cleaned.append(t)
    return cleaned


def get_embeddings(
    texts: List[str],
    model_key: str,
    instruction: Optional[str] = None,
):
    data = load_model(model_key)
    inst = resolve_instruction(model_key, instruction)
    # 文档索引:ReadAny 不会传 instruction 字段;默认 query instruct 对书 chunk 不合适
    # 调用方传 instruction="" 可关闭;未传时仍用默认(兼容检索 query)
    texts = apply_instruction(texts, inst)
    arr = infer_batch(data, texts)
    return arr.astype(np.float32).tolist(), data["dim"], data["actual_device"]


# ==================== OpenAI API ====================
class EmbeddingRequest(BaseModel):
    input: Union[str, List[str]]
    model: Optional[str] = Field(default=None)
    encoding_format: Optional[str] = "float"
    # 扩展字段:Qwen query instruct;传 "" 表示文档侧不用 instruct
    instruction: Optional[str] = Field(
        default=None,
        description="Optional task instruction for Qwen-style models. Empty string disables.",
    )


class EmbeddingData(BaseModel):
    object: str = "embedding"
    embedding: List[float]
    index: int


class EmbeddingResponse(BaseModel):
    object: str = "list"
    data: List[EmbeddingData]
    model: str
    usage: dict


@app.get("/")
async def root():
    return {
        "service": "openvino-embedding-lite",
        "docs": "/docs",
        "embeddings": "/v1/embeddings",
        "health": "/health",
        "models": "/v1/models",
        "default_model": DEFAULT_MODEL_KEY,
    }


@app.get("/health")
async def health():
    return {
        "status": "ok",
        "mode": "lite",
        "requested_device": DEVICE,
        "max_length": MAX_LENGTH,
        "cpu_max_batch": CPU_MAX_BATCH,
        "max_inputs_per_request": MAX_INPUTS_PER_REQUEST,
        "max_chars_per_input": MAX_CHARS_PER_INPUT,
        "force_static_pad": FORCE_STATIC_PAD,
        "lazy_load": LAZY_LOAD,
        "default_model": DEFAULT_MODEL_KEY,
        "use_default_instruction": USE_DEFAULT_INSTRUCTION,
        "auth_required": bool(API_KEY),
        "cpu": _detect_cpu(),
        "loaded": {k: v["actual_device"] for k, v in models_cache.items()},
        "available_models": list(AVAILABLE_MODELS.keys()),
    }


@app.get("/v1/models")
async def list_models():
    return {
        "object": "list",
        "data": [
            {
                "id": key,
                "object": "model",
                "created": int(time.time()),
                "owned_by": "local-openvino-lite",
                "description": cfg["desc"],
                "dimensions": cfg["dim"],
                "pooling": cfg.get("pooling"),
            }
            for key, cfg in AVAILABLE_MODELS.items()
        ],
    }


@app.post("/v1/embeddings", response_model=EmbeddingResponse)
async def create_embeddings(request: EmbeddingRequest):
    try:
        texts = [request.input] if isinstance(request.input, str) else request.input
        if not texts:
            raise HTTPException(status_code=400, detail="input cannot be empty")
        if len(texts) > MAX_INPUTS_PER_REQUEST:
            raise HTTPException(
                status_code=400,
                detail=(
                    f"too many inputs: {len(texts)} > MAX_INPUTS_PER_REQUEST={MAX_INPUTS_PER_REQUEST}. "
                    "Client should batch (ReadAny already uses 8)."
                ),
            )
        texts = sanitize_texts(texts)
        model_key = request.model if request.model in AVAILABLE_MODELS else DEFAULT_MODEL_KEY
        # 文档向量化:客户端未传 instruction 时,对多条长文本默认不套 query instruct
        # 单条短 query 仍可用默认 instruct
        instruction = request.instruction
        if instruction is None and len(texts) >= 2:
            instruction = ""
        logger.info(
            "embed req model=%s n=%s chars=%s max_len=%s",
            model_key,
            len(texts),
            [len(t) for t in texts[:8]],
            MAX_LENGTH,
        )
        vectors, _, _ = get_embeddings(texts, model_key, instruction=instruction)
        data = [EmbeddingData(embedding=v, index=i) for i, v in enumerate(vectors)]
        total_tokens = sum(max(1, len(t)) for t in texts)
        return EmbeddingResponse(
            data=data,
            model=model_key,
            usage={"prompt_tokens": total_tokens, "total_tokens": total_tokens},
        )
    except HTTPException:
        raise
    except Exception as e:
        # 把真实异常打到 Space 日志;响应里给可诊断摘要
        tb = traceback.format_exc(limit=8)
        logger.error("embed 500: %s\n%s", e, tb)
        detail = f"{type(e).__name__}: {e}"
        if len(detail) > 800:
            detail = detail[:800] + "..."
        raise HTTPException(status_code=500, detail=detail)


if __name__ == "__main__":
    print("=" * 60)
    print("OpenVINO Lite Embedding Server")
    print(f"Project : {PROJECT_ROOT}")
    print(f"API     : http://localhost:{PORT}/v1/embeddings")
    print(f"Docs    : http://localhost:{PORT}/docs")
    print(f"Health  : http://localhost:{PORT}/health")
    print(f"Model   : {DEFAULT_MODEL_KEY}")
    print(f"Device  : {DEVICE} | MAX_LENGTH={MAX_LENGTH} | LAZY_LOAD={LAZY_LOAD}")
    print("=" * 60)

    if not LAZY_LOAD:
        try:
            load_model(DEFAULT_MODEL_KEY)
        except Exception as e:
            print(f"[preload] failed: {e}")

    # workers=1: one model copy, lower memory
    uvicorn.run(app, host="0.0.0.0", port=PORT, workers=1, log_level="info")