Views
No views yet
onnxruntime-gpu package is required to leverage the CUDAExecutionProvider.pip install fastapi uvicorn onnxruntime-gpu transformers torchapp.py)1import numpy as np
2import onnxruntime as ort
3from transformers import AutoTokenizer
4from fastapi import FastAPI
5from pydantic import BaseModel
6
7app = FastAPI()
8
9# 1. Load Tokenizer and ONNX Session
10tokenizer = AutoTokenizer.from_pretrained("./tokenizer_path")
11session = ort.InferenceSession(
12 "model.onnx",
13 providers=['CUDAExecutionProvider', 'CPUExecutionProvider']
14)
15
16class Query(BaseModel):
17 text: str
18
19@app.post("/embed")
20async def get_embeddings(query: Query):
21 # 2. Tokenization
22 inputs = tokenizer(query.text, return_tensors="np", padding=True, truncation=True)
23
24 # 3. ONNX Inference
25 # Ensure input names match your specific ONNX model (usually 'input_ids', 'attention_mask')
26 onnx_inputs = {node.name: inputs[node.name] for node in session.get_inputs()}
27 outputs = session.run(None, onnx_inputs)
28
29 # 4. Return result (usually the first output)
30 embeddings = outputs[0].tolist()
31 return {"embeddings": embeddings}uvicorn app:app --host 0.0.0.0 --port 80001curl -X POST "http://localhost:8000/embed" \
2 -H "Content-Type: application/json" \
3 -d @- <<EOFEOF
4 {
5 "model": "jina-embeddings-v4",
6 "task": "text-matching",
7 "input": [
8 {
9 "text": "A beautiful sunset over the beach"
10 },
11 {
12 "text": "Un beau coucher de soleil sur la plage"
13 },
14 {
15 "text": "Ein wunderschöner Sonnenuntergang am Strand"
16 },
17 {
18 "text": "Ένα όμορφο ηλιοβασίλεμα πάνω από την παραλία"
19 },
20 {
21 "text": "Un bellissimo tramonto sulla spiaggia"
22 },
23 {
24 "image": "https://i.ibb.co/nQNGqL0/beach1.jpg"
25 },
26 {
27 "image": "https://i.ibb.co/r5w8hG8/beach2.jpg"
28 }
29 ]
30 }
31EOFEOFInferenceSession, placing 'CUDAExecutionProvider' first is critical. If the GPU drivers are missing, it will gracefully fall back to 'CPUExecutionProvider'.[node.name for node in session.get_inputs()], as some models use token_type_ids while others do not.