n1th1sh commited on
Commit
59badaa
Β·
verified Β·
1 Parent(s): 91b8be2

Upload 7 files

Browse files
Files changed (2) hide show
  1. README.md +10 -1
  2. app.py +62 -7
README.md CHANGED
@@ -66,7 +66,16 @@ different host, if it ever has to run apart from the models.)
66
  β†’ `{entities: [{type, text, start, end, confidence}], nested, redacted_text, model, processing_time_ms}`
67
  - Failures are never 200-with-empty, so DSPM records scan **errors**, not false "clean".
68
  - `MAX_INPUT_CHARS = 80_000` here must be β‰₯ `DETECT_MAX_CHARS` in `pii.ts`.
69
- - `GET /health` β†’ `{status, model, engine, threads, classes, max_input_chars, auth_configured, docclass, copilot}`.
 
 
 
 
 
 
 
 
 
70
 
71
  ## Document classification (`docclass.py`)
72
 
 
66
  β†’ `{entities: [{type, text, start, end, confidence}], nested, redacted_text, model, processing_time_ms}`
67
  - Failures are never 200-with-empty, so DSPM records scan **errors**, not false "clean".
68
  - `MAX_INPUT_CHARS = 80_000` here must be β‰₯ `DETECT_MAX_CHARS` in `pii.ts`.
69
+ - `GET /health` β†’ `{status, model, engine, threads, classes, pii_sessions, threads_per_session, pii_busy, max_input_chars, auth_configured, docclass, copilot}`.
70
+ - **Parallel requests:** the PII model is loaded `PII_SESSIONS` times (1–8; default one per 4 vCPU:
71
+ 2 on 8 vCPU, 1 on the free tier), with the cores split between the copies. Each request takes a
72
+ free copy and waits if none is free. Each copy holds its own weights, so watch memory before
73
+ raising it. Pair it with `PII_MODEL_CONCURRENCY` on the CLOAK server (about 2 per copy).
74
+ - **Stress test:** `tools/model-stress/stress_detect.py` at the repo root (standard library only, not
75
+ part of the Space image). Set `CLOAK_MODEL_SECRET` to the Space's `API_SECRET`, then
76
+ `python tools/model-stress/stress_detect.py --url https://<space>.hf.space`. It steps
77
+ through 1, 2, 4, 8, 16 parallel requests and reports throughput, latency, errors, busy copies and
78
+ where the Space saturates. Run it only against your own Space, outside client traffic hours.
79
 
80
  ## Document classification (`docclass.py`)
81
 
app.py CHANGED
@@ -24,7 +24,10 @@ import hmac
24
  import json
25
  import logging
26
  import os
 
 
27
  import time
 
28
 
29
  import numpy as np
30
  import onnxruntime as ort
@@ -127,13 +130,55 @@ with open(_config_path, encoding="utf-8") as fh:
127
  _id2label = {int(k): v for k, v in _config["id2label"].items()}
128
  _tokenizer = AutoTokenizer.from_pretrained(MODEL_REPO, subfolder="tokenizer", token=HF_TOKEN)
129
 
130
- _opts = ort.SessionOptions()
131
- _opts.intra_op_num_threads = _n_threads
132
- _opts.inter_op_num_threads = 1
133
- _opts.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
134
- _sess = ort.InferenceSession(_int8_path, sess_options=_opts, providers=["CPUExecutionProvider"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
 
136
- log.info("ONNX INT8 session ready: %d threads, %d classes", _n_threads, len(_id2label))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
 
138
 
139
  # ── Inference ─────────────────────────────────────────────────────────────────
@@ -196,6 +241,12 @@ def detect(text: str, threshold: float = THRESHOLD):
196
 
197
  n_pre, n_suf = len(_PREFIX_IDS), len(_SUFFIX_IDS)
198
  best: dict = {}
 
 
 
 
 
 
199
  for s, e in windows:
200
  # Each window is run at its real length: no padding, so no pad-token
201
  # artifacts in the last (shortest) window.
@@ -203,7 +254,7 @@ def detect(text: str, threshold: float = THRESHOLD):
203
  offsets = np.array([(0, 0)] * n_pre + offs[s:e] + [(0, 0)] * n_suf, dtype=np.int64)
204
  input_ids = np.asarray([w_ids], dtype=np.int64)
205
  feed = {"input_ids": input_ids, "attention_mask": np.ones_like(input_ids)}
206
- logits = _sess.run(["logits"], feed)[0][0] # [classes, L, L]
207
 
208
  cidx, sidx, eidx = np.where(logits > threshold)
209
  if len(cidx) == 0:
@@ -228,6 +279,8 @@ def detect(text: str, threshold: float = THRESHOLD):
228
  "score": float(sc),
229
  }
230
 
 
 
231
  # Drop absurdly long spans, but never on short inputs (a lone email/name
232
  # legitimately covers ~100% of a short text).
233
  max_span = max(0.5 * len(text), 100)
@@ -322,6 +375,8 @@ def health():
322
  # failed scans.
323
  return {"status": "ok", "model": MODEL_REPO, "engine": "onnx-int8-cpu",
324
  "threads": _n_threads, "classes": len(_id2label),
 
 
325
  "max_input_chars": MAX_INPUT_CHARS,
326
  "auth_configured": bool(API_SECRET),
327
  "docclass": docclass.status(),
 
24
  import json
25
  import logging
26
  import os
27
+ import queue
28
+ import threading
29
  import time
30
+ from contextlib import contextmanager
31
 
32
  import numpy as np
33
  import onnxruntime as ort
 
130
  _id2label = {int(k): v for k, v in _config["id2label"].items()}
131
  _tokenizer = AutoTokenizer.from_pretrained(MODEL_REPO, subfolder="tokenizer", token=HF_TOKEN)
132
 
133
+ # ── Session pool: several copies of the model, each on its own share of the cores ──
134
+ # One session using every core runs one request at a time well, but /detect is a sync
135
+ # route, so FastAPI already runs requests in parallel threads; two of them on one
136
+ # 8-thread session ask for 16 threads on 8 cores and both slow down. Instead, load
137
+ # PII_SESSIONS copies with the cores split between them; a request takes whichever
138
+ # copy is free and waits if none is. Default: one copy per 4 cores (2 on 8 vCPU,
139
+ # 1 on the free 2-vCPU tier, i.e. unchanged there). Each copy holds its own weights,
140
+ # so memory for the PII model grows with the count: check /health and the Space's
141
+ # memory graph before raising it.
142
+
143
+ def _env_int(name: str, default: int, lo: int, hi: int) -> int:
144
+ try:
145
+ v = int(os.getenv(name, ""))
146
+ except ValueError:
147
+ return default
148
+ return max(lo, min(hi, v))
149
+
150
+
151
+ PII_SESSIONS = _env_int("PII_SESSIONS", max(1, min(4, _n_threads // 4)), 1, 8)
152
+ _threads_per_session = max(1, _n_threads // PII_SESSIONS)
153
 
154
+ _pool: "queue.Queue[ort.InferenceSession]" = queue.Queue()
155
+ for _i in range(PII_SESSIONS):
156
+ _opts = ort.SessionOptions()
157
+ _opts.intra_op_num_threads = _threads_per_session
158
+ _opts.inter_op_num_threads = 1
159
+ _opts.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
160
+ _pool.put(ort.InferenceSession(_int8_path, sess_options=_opts, providers=["CPUExecutionProvider"]))
161
+
162
+ _busy = 0 # copies running a request right now (reported by /health)
163
+ _busy_lock = threading.Lock()
164
+
165
+ log.info("ONNX INT8 ready: %d session(s) x %d threads, %d classes",
166
+ PII_SESSIONS, _threads_per_session, len(_id2label))
167
+
168
+
169
+ @contextmanager
170
+ def _session():
171
+ """Borrow a free model copy for one whole request (all its windows)."""
172
+ global _busy
173
+ sess = _pool.get()
174
+ with _busy_lock:
175
+ _busy += 1
176
+ try:
177
+ yield sess
178
+ finally:
179
+ with _busy_lock:
180
+ _busy -= 1
181
+ _pool.put(sess)
182
 
183
 
184
  # ── Inference ─────────────────────────────────────────────────────────────────
 
241
 
242
  n_pre, n_suf = len(_PREFIX_IDS), len(_SUFFIX_IDS)
243
  best: dict = {}
244
+ with _session() as sess:
245
+ _score_windows(sess, ids, offs, windows, n_pre, n_suf, threshold, best)
246
+ return _finish(text, best)
247
+
248
+
249
+ def _score_windows(sess, ids, offs, windows, n_pre, n_suf, threshold, best):
250
  for s, e in windows:
251
  # Each window is run at its real length: no padding, so no pad-token
252
  # artifacts in the last (shortest) window.
 
254
  offsets = np.array([(0, 0)] * n_pre + offs[s:e] + [(0, 0)] * n_suf, dtype=np.int64)
255
  input_ids = np.asarray([w_ids], dtype=np.int64)
256
  feed = {"input_ids": input_ids, "attention_mask": np.ones_like(input_ids)}
257
+ logits = sess.run(["logits"], feed)[0][0] # [classes, L, L]
258
 
259
  cidx, sidx, eidx = np.where(logits > threshold)
260
  if len(cidx) == 0:
 
279
  "score": float(sc),
280
  }
281
 
282
+
283
+ def _finish(text: str, best: dict):
284
  # Drop absurdly long spans, but never on short inputs (a lone email/name
285
  # legitimately covers ~100% of a short text).
286
  max_span = max(0.5 * len(text), 100)
 
375
  # failed scans.
376
  return {"status": "ok", "model": MODEL_REPO, "engine": "onnx-int8-cpu",
377
  "threads": _n_threads, "classes": len(_id2label),
378
+ "pii_sessions": PII_SESSIONS, "threads_per_session": _threads_per_session,
379
+ "pii_busy": _busy,
380
  "max_input_chars": MAX_INPUT_CHARS,
381
  "auth_configured": bool(API_SECRET),
382
  "docclass": docclass.status(),