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 
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
import os
import time
from pathlib import Path
from typing import Dict, List, Optional, Union

# ==================== 项目路径 ====================
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 = {
    "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"
        ),
    },
    "bge-small-zh-v1.5": {
        "id": "BAAI/bge-small-zh-v1.5",
        "path": PROJECT_ROOT / "models" / "bge-small-zh-v1.5",
        "dim": 512,
        "desc": "Chinese fast embedding (quality/speed balanced)",
        "pooling": "mean",
        "padding_side": "right",
        "default_instruction": None,
    },
}

DEFAULT_MODEL_KEY = os.environ.get("DEFAULT_MODEL", "qwen3-embedding-0.6b")
if DEFAULT_MODEL_KEY not in AVAILABLE_MODELS:
    DEFAULT_MODEL_KEY = "qwen3-embedding-0.6b"

# 性能设备:本地可 NPU;HF Spaces / 无 NPU 时自动回退 CPU
DEVICE = os.environ.get("DEVICE", "NPU").upper()  # NPU | CPU | AUTO
# 序列长度上限(运行时 pad/truncate,不写死在 IR 里;NPU 编译时会按此静态化)
# 建议:HF 免费 CPU 512~1024;本机 1024~2048;再大延迟/内存线性涨
MAX_LENGTH = int(os.environ.get("MAX_LENGTH", "1024"))
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 批量上限(NPU 固定为 1)
CPU_MAX_BATCH = int(os.environ.get("CPU_MAX_BATCH", "8"))
# 是否在未显式传 instruction 时使用模型 default_instruction
USE_DEFAULT_INSTRUCTION = os.environ.get("USE_DEFAULT_INSTRUCTION", "1").lower() in (
    "1",
    "true",
    "yes",
)
# ==================================================

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

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=["*"],
)

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 动态亦可,静态更稳
            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}")
            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 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 = tokenizer(
                [t],
                padding="max_length",
                truncation=True,
                max_length=MAX_LENGTH,
                return_tensors="np",
            )
            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: true batch
    all_emb = []
    for i in range(0, len(texts), CPU_MAX_BATCH):
        chunk = texts[i : i + CPU_MAX_BATCH]
        enc = tokenizer(
            chunk,
            padding="max_length",
            truncation=True,
            max_length=MAX_LENGTH,
            return_tensors="np",
        )
        result = compiled(_feed_dict(data, enc))
        out = np.array(result[data["output"]])
        emb = _pool(data, out, enc["attention_mask"])
        all_emb.append(l2_normalize(emb))
    return np.concatenate(all_emb, axis=0)


def get_embeddings(
    texts: List[str],
    model_key: str,
    instruction: Optional[str] = None,
):
    data = load_model(model_key)
    inst = resolve_instruction(model_key, instruction)
    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,
        "lazy_load": LAZY_LOAD,
        "default_model": DEFAULT_MODEL_KEY,
        "use_default_instruction": USE_DEFAULT_INSTRUCTION,
        "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")
        texts = [t if isinstance(t, str) else str(t) for t in texts]

        model_key = request.model if request.model in AVAILABLE_MODELS else DEFAULT_MODEL_KEY
        vectors, _, _ = get_embeddings(texts, model_key, instruction=request.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:
        raise HTTPException(status_code=500, detail=str(e))


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")