File size: 5,043 Bytes
19d3bef
f4ae92f
 
19d3bef
f4ae92f
 
 
 
 
 
 
fd47265
19d3bef
fd47265
f4ae92f
fd47265
f4ae92f
 
19d3bef
 
f4ae92f
19d3bef
 
f4ae92f
 
 
fd47265
f4ae92f
 
 
 
 
 
 
 
fd47265
 
 
 
19d3bef
fd47265
19d3bef
17fff34
fd47265
19d3bef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd47265
19d3bef
fd47265
17fff34
fd47265
19d3bef
 
 
 
 
 
 
 
 
 
 
 
fd47265
 
 
 
f4ae92f
 
 
 
19d3bef
 
f4ae92f
19d3bef
 
 
 
 
 
 
 
 
 
 
 
f4ae92f
 
 
19d3bef
 
 
 
 
 
 
 
f4ae92f
19d3bef
fd47265
f4ae92f
 
 
 
fd47265
f4ae92f
 
 
 
fd47265
19d3bef
 
 
 
 
 
 
 
 
 
 
 
 
fd47265
19d3bef
 
 
 
 
 
 
 
 
 
 
 
fd47265
 
 
 
 
19d3bef
fd47265
 
 
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
import time
import os
import gc
import json
import nltk
from contextlib import asynccontextmanager
from typing import List

from fastapi import FastAPI
from pydantic import BaseModel
from transformers import AutoTokenizer
from prometheus_fastapi_instrumentator import Instrumentator
from prometheus_client import Histogram, Counter
from nltk.tokenize import word_tokenize

# Internal package imports
from mentioned.inference import (
    create_inference_model,
    compile_detector,
    compile_labeler,
    ONNXMentionDetectorPipeline,
    ONNXMentionLabelerPipeline,
    InferenceMentionLabeler
)


def setup_nltk():
    resources = ["punkt", "punkt_tab"]
    for res in resources:
        try:
            nltk.data.find(f"tokenizers/{res}")
        except LookupError:
            nltk.download(res)


class TextRequest(BaseModel):
    texts: List[str]


MENTION_CONFIDENCE = Histogram(
    "mention_detector_confidence",
    "Distribution of prediction confidence scores for detector.",
    buckets=[0.1, 0.3, 0.5, 0.7, 0.8, 0.9, 1.0],
)
ENTITY_CONFIDENCE = Histogram(
    "entity_labeler_confidence",
    "Distribution of prediction confidence scores for labeler."
)
ENTITY_LABEL_COUNTS = Counter(
    "entity_label_total",
    "Total count of predicted entity labels",
    ["label_name"]
)
INPUT_TOKENS = Histogram(
    "mention_input_tokens_count",
    "Number of tokens per input document",
    buckets=[1, 5, 10, 20, 50, 100, 250, 500]
)
MENTION_DENSITY = Histogram(
    "mention_density_ratio",
    "Ratio of mentions to total tokens in a document",
    buckets=[0.01, 0.05, 0.1, 0.2, 0.5]
)
MENTIONS_PER_DOC = Histogram(
    "mention_detector_count",
    "Number of mentions detected per document",
    buckets=[0, 1, 2, 5, 10, 20, 50],
)

INFERENCE_LATENCY = Histogram(
    "inference_duration_seconds",
    "Time spent in the model prediction pipeline",
    buckets=[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0]
)

REPO_ID = os.getenv("REPO_ID", "kadarakos/entity-labeler-poc")
ENCODER_ID = os.getenv("ENCODER_ID", "distilroberta-base")
MODEL_FACTORY = os.getenv("MODEL_FACTORY", "model_v2")
DATA_FACTORY = os.getenv("DATA_FACTORY", "litbank_entities")
ENGINE_DIR = "model_v2_artifact"
MODEL_PATH = os.path.join(ENGINE_DIR, "model.onnx")

state = {}
setup_nltk()


@asynccontextmanager
async def lifespan(app: FastAPI):
    """JIT compilation and loading for both Detector and Labeler."""

    if not os.path.exists(MODEL_PATH):
        print(f"🏗️ Engine not found. Compiling {MODEL_FACTORY} from {REPO_ID}...")
        torch_model = create_inference_model(REPO_ID, ENCODER_ID, MODEL_FACTORY, DATA_FACTORY)

        if isinstance(torch_model, InferenceMentionLabeler):
            compile_labeler(torch_model, ENGINE_DIR)
            with open(os.path.join(ENGINE_DIR, "config.json"), "w") as f:
                json.dump({"id2label": torch_model.id2label, "type": "labeler"}, f)
        else:
            compile_detector(torch_model, ENGINE_DIR)
            with open(os.path.join(ENGINE_DIR, "config.json"), "w") as f:
                json.dump({"type": "detector"}, f)

        tokenizer = torch_model.tokenizer
        del torch_model
        gc.collect()

    tokenizer = AutoTokenizer.from_pretrained(ENGINE_DIR)
    with open(os.path.join(ENGINE_DIR, "config.json"), "r") as f:
        config = json.load(f)

    if config.get("type") == "labeler":
        id2label = {int(k): v for k, v in config["id2label"].items()}
        state["pipeline"] = ONNXMentionLabelerPipeline(MODEL_PATH, tokenizer, id2label)
    else:
        state["pipeline"] = ONNXMentionDetectorPipeline(MODEL_PATH, tokenizer)

    yield
    state.clear()

app = FastAPI(lifespan=lifespan)
Instrumentator().instrument(app).expose(app)


@app.post("/predict")
async def predict(request: TextRequest):
    docs = [word_tokenize(t) for t in request.texts]
    start_time = time.perf_counter()
    results = state["pipeline"].predict(docs)
    INFERENCE_LATENCY.observe(time.perf_counter() - start_time)

    for doc, doc_mentions in zip(docs, results):
        token_count = len(doc)
        mention_count = len(doc_mentions)
        
        # Input/Density metrics
        INPUT_TOKENS.observe(token_count)
        MENTIONS_PER_DOC.observe(mention_count)
        if token_count > 0:
            MENTION_DENSITY.observe(mention_count / token_count)

        for m in doc_mentions:
            # Basic detector confidence
            MENTION_CONFIDENCE.observe(m.get("score", 0))
            
            # Labeler specific metrics
            if "label" in m:
                ENTITY_LABEL_COUNTS.labels(label_name=m["label"]).inc()
                # Ensure we only observe label_score if it exists in the output
                if "label_score" in m:
                    ENTITY_CONFIDENCE.observe(m["label_score"])
                
    return {"results": results, "model_repo": REPO_ID}


@app.get("/")
def home():
    return {
        "message": "Mention Detector and Labeler API.",
        "docs": "/docs",
        "metrics": "/metrics",
    }