feat(ml): add isolated embeddings service and scoped client
This commit is contained in:
1 parent
46c185d928
commit
0c7897d695
13 files changed
+1112
No files matched your search
@@ -0,0 +1,5 @@
|
||||
*
|
||||
!Dockerfile
|
||||
!requirements.txt
|
||||
!pages_ml.py
|
||||
!train.py
|
||||
@@ -0,0 +1,5 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.venv/
|
||||
models/
|
||||
*.jsonl
|
||||
@@ -0,0 +1,10 @@
|
||||
FROM python:3.12-slim-bookworm
|
||||
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 PYTHONHASHSEED=0 \
|
||||
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 MKL_NUM_THREADS=1
|
||||
WORKDIR /app
|
||||
COPY requirements.txt ./
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
COPY pages_ml.py train.py ./
|
||||
USER 65532:65532
|
||||
EXPOSE 8010
|
||||
CMD ["gunicorn", "--bind", "0.0.0.0:8010", "--workers", "1", "--worker-class", "gthread", "--threads", "2", "--timeout", "60", "--worker-tmp-dir", "/tmp", "--no-control-socket", "--limit-request-line", "1024", "--limit-request-fields", "30", "pages_ml:create_app()"]
|
||||
@@ -0,0 +1,265 @@
|
||||
"""Internal stateless ML API. No Pages database access or document fetching.
|
||||
|
||||
Run with one gunicorn worker, two threads: inference is serialized while health
|
||||
checks and busy responses remain available. Never publish this API to browsers.
|
||||
"""
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import threading
|
||||
import unicodedata
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
VERSION = "1"
|
||||
TOKENIZER = "unicode-cjk-bigram-v1"
|
||||
MAX_BODY = 128 * 1024
|
||||
MAX_ITEMS = 16
|
||||
MAX_TEXT_BYTES = 6000
|
||||
MAX_DIMENSIONS = 1536
|
||||
MAX_RESPONSE = 2 * 1024 * 1024
|
||||
|
||||
|
||||
class Failure(Exception):
|
||||
def __init__(self, status, code):
|
||||
self.status, self.code = status, code
|
||||
|
||||
|
||||
def digest(data):
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def valid_uuid(value):
|
||||
try:
|
||||
return isinstance(value, str) and str(uuid.UUID(value)) == value
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def tokens(text):
|
||||
"""Deterministic baseline, not a Japanese morphological analyzer."""
|
||||
text = unicodedata.normalize("NFKC", text).casefold()
|
||||
result = []
|
||||
for part in re.findall(r"[\u3040-\u30ff\u3400-\u9fff]+|[^\W_\u3040-\u30ff\u3400-\u9fff]+", text):
|
||||
if re.fullmatch(r"[\u3040-\u30ff\u3400-\u9fff]+", part):
|
||||
result.extend(part[i:i+2] for i in range(max(1, len(part)-1)))
|
||||
else:
|
||||
result.append(part)
|
||||
return result
|
||||
|
||||
|
||||
def validate_request(data):
|
||||
fields = {"protocol", "domain_uuid", "scope_uuid", "provider", "model", "dimensions", "inputs", "allow_external"}
|
||||
if not isinstance(data, dict) or set(data) - fields or data.get("protocol") != VERSION:
|
||||
raise Failure(400, "invalid_request")
|
||||
if not valid_uuid(data.get("domain_uuid")) or not valid_uuid(data.get("scope_uuid")):
|
||||
raise Failure(400, "invalid_scope")
|
||||
dims = data.get("dimensions")
|
||||
if type(dims) is not int or not 1 <= dims <= MAX_DIMENSIONS:
|
||||
raise Failure(400, "invalid_dimensions")
|
||||
if data.get("provider") not in ("openai", "doc2vec") or not isinstance(data.get("model"), str):
|
||||
raise Failure(400, "invalid_provider")
|
||||
if "allow_external" in data and type(data["allow_external"]) is not bool:
|
||||
raise Failure(400, "invalid_external_consent")
|
||||
inputs = data.get("inputs")
|
||||
if not isinstance(inputs, list) or not 1 <= len(inputs) <= MAX_ITEMS:
|
||||
raise Failure(400, "invalid_inputs")
|
||||
ids = set()
|
||||
for item in inputs:
|
||||
if not isinstance(item, dict) or set(item) != {"id", "text"}:
|
||||
raise Failure(400, "invalid_input")
|
||||
ident, text = item["id"], item["text"]
|
||||
if not isinstance(ident, str) or not re.fullmatch(r"[A-Za-z0-9_.:-]{1,128}", ident) or ident in ids:
|
||||
raise Failure(400, "invalid_input_id")
|
||||
if not isinstance(text, str) or not text.strip() or len(text.encode("utf-8")) > MAX_TEXT_BYTES:
|
||||
raise Failure(400, "invalid_text")
|
||||
ids.add(ident)
|
||||
return data
|
||||
|
||||
|
||||
def validate_vectors(vectors, count, dims):
|
||||
if not isinstance(vectors, list) or len(vectors) != count:
|
||||
raise Failure(502, "invalid_provider_output")
|
||||
for vector in vectors:
|
||||
if not isinstance(vector, list) or len(vector) != dims or any(
|
||||
type(x) not in (int, float) or not -1e100 <= x <= 1e100 or not math.isfinite(x) for x in vector
|
||||
) or not any(x != 0 for x in vector):
|
||||
raise Failure(502, "invalid_provider_output")
|
||||
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
class Engine:
|
||||
def __init__(self, model_root, external_enabled=False, api_key=""):
|
||||
self.model_root = Path(model_root)
|
||||
self.external_enabled = external_enabled
|
||||
self.api_key = api_key
|
||||
self.cached = None # One resident model at most, serialized inference.
|
||||
|
||||
def embed(self, data):
|
||||
if data["provider"] == "openai":
|
||||
vectors, revision, usage = self.openai(data)
|
||||
tokenizer = "provider"
|
||||
else:
|
||||
vectors, revision, usage = self.doc2vec(data)
|
||||
tokenizer = TOKENIZER
|
||||
validate_vectors(vectors, len(data["inputs"]), data["dimensions"])
|
||||
return {
|
||||
"protocol": VERSION, "domain_uuid": data["domain_uuid"], "scope_uuid": data["scope_uuid"],
|
||||
"provider": data["provider"], "model": data["model"], "model_revision": revision,
|
||||
"dimensions": data["dimensions"], "tokenizer": tokenizer, "usage": usage,
|
||||
"outputs": [{"id": item["id"], "input_sha256": digest(item["text"].encode("utf-8")), "vector": vector}
|
||||
for item, vector in zip(data["inputs"], vectors)],
|
||||
}
|
||||
|
||||
def openai(self, data):
|
||||
if not self.external_enabled or data.get("allow_external") is not True or not self.api_key:
|
||||
raise Failure(403, "external_disabled")
|
||||
if data["model"] != "text-embedding-3-small":
|
||||
raise Failure(400, "unsupported_model")
|
||||
# Fixed HTTPS endpoint; request bodies cannot choose an origin or API key.
|
||||
body = json.dumps({"model": data["model"], "input": [x["text"] for x in data["inputs"]],
|
||||
"dimensions": data["dimensions"], "encoding_format": "float"}).encode()
|
||||
request = urllib.request.Request("https://api.openai.com/v1/embeddings", body,
|
||||
{"Authorization": "Bearer " + self.api_key, "Content-Type": "application/json"})
|
||||
try:
|
||||
with urllib.request.build_opener(NoRedirect()).open(request, timeout=30) as response:
|
||||
raw = response.read(MAX_RESPONSE + 1)
|
||||
if len(raw) > MAX_RESPONSE:
|
||||
raise Failure(502, "invalid_provider_output")
|
||||
result = json.loads(raw)
|
||||
entries = result["data"]
|
||||
if any(type(x["index"]) is not int for x in entries) or sorted(x["index"] for x in entries) != list(range(len(data["inputs"]))):
|
||||
raise ValueError("indices")
|
||||
if result["model"] != data["model"]:
|
||||
raise ValueError("model")
|
||||
usage = result["usage"]["total_tokens"]
|
||||
if type(usage) is not int or usage < 0:
|
||||
raise ValueError("usage")
|
||||
return [x["embedding"] for x in sorted(entries, key=lambda x: x["index"])], result["model"], {"total_tokens": usage}
|
||||
except urllib.error.HTTPError as error:
|
||||
# Never expose upstream bodies (may include input or secrets).
|
||||
raise Failure(429 if error.code == 429 else 502, "provider_rate_limited" if error.code == 429 else "provider_failed") from None
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
raise Failure(502, "provider_failed") from None
|
||||
|
||||
def doc2vec(self, data):
|
||||
model_id = data["model"]
|
||||
if not re.fullmatch(r"[0-9a-f]{64}", model_id):
|
||||
raise Failure(400, "invalid_model")
|
||||
directory = self.model_root / data["domain_uuid"] / data["scope_uuid"] / model_id
|
||||
# Operator-created read-only models only; no uploads or arbitrary paths.
|
||||
try:
|
||||
if directory.is_symlink() or not directory.resolve().is_relative_to(self.model_root.resolve()):
|
||||
raise Failure(404, "model_not_found")
|
||||
manifest_path = directory / "manifest.json"
|
||||
if manifest_path.is_symlink() or manifest_path.stat().st_size > 8192:
|
||||
raise Failure(409, "model_metadata_mismatch")
|
||||
manifest = json.loads(manifest_path.read_text())
|
||||
expected = {"domain_uuid": data["domain_uuid"], "scope_uuid": data["scope_uuid"],
|
||||
"tokenizer": TOKENIZER, "dimensions": data["dimensions"], "model_sha256": model_id}
|
||||
if any(manifest.get(k) != v for k, v in expected.items()):
|
||||
raise Failure(409, "model_metadata_mismatch")
|
||||
path = directory / "model.bin"
|
||||
if path.is_symlink():
|
||||
raise Failure(409, "model_metadata_mismatch")
|
||||
stat = path.stat()
|
||||
key = (str(directory), stat.st_ino, stat.st_size, stat.st_mtime_ns)
|
||||
if self.cached is None or self.cached[0] != key:
|
||||
self.cached = None
|
||||
if stat.st_size > 256 * 1024 * 1024:
|
||||
raise Failure(413, "model_too_large")
|
||||
if digest(path.read_bytes()) != model_id:
|
||||
raise Failure(409, "model_digest_mismatch")
|
||||
from gensim.models.doc2vec import Doc2Vec
|
||||
model = Doc2Vec.load(str(path))
|
||||
if model.vector_size != data["dimensions"]:
|
||||
raise Failure(409, "model_metadata_mismatch")
|
||||
self.cached = (key, model)
|
||||
model = self.cached[1]
|
||||
vectors = []
|
||||
for item in data["inputs"]:
|
||||
words = tokens(item["text"])
|
||||
if not any(word in model.wv for word in words):
|
||||
raise Failure(422, "no_known_tokens")
|
||||
model.random.seed(int(digest(item["text"].encode())[:8], 16))
|
||||
vectors.append(model.infer_vector(words, epochs=30).tolist())
|
||||
return vectors, model_id, {"total_tokens": 0}
|
||||
except FileNotFoundError:
|
||||
self.cached = None
|
||||
raise Failure(404, "model_not_found") from None
|
||||
|
||||
|
||||
class Application:
|
||||
def __init__(self, token, engine):
|
||||
if not re.fullmatch(r"[A-Za-z0-9_-]{32,256}", token):
|
||||
raise ValueError("ML token must contain 32-256 URL-safe characters")
|
||||
self.token, self.engine = token, engine
|
||||
self.slot = threading.BoundedSemaphore(1)
|
||||
|
||||
def __call__(self, environ, start_response):
|
||||
try:
|
||||
method, path = environ.get("REQUEST_METHOD"), environ.get("PATH_INFO")
|
||||
if method == "GET" and path == "/healthz":
|
||||
return self.response(start_response, 200, {"status": "ok", "protocol": VERSION})
|
||||
authorization = environ.get("HTTP_AUTHORIZATION", "").encode()
|
||||
if not hmac.compare_digest(authorization, ("Bearer " + self.token).encode()):
|
||||
raise Failure(401, "unauthorized")
|
||||
if method != "POST" or path != "/v1/embeddings":
|
||||
raise Failure(404, "not_found")
|
||||
if environ.get("CONTENT_TYPE", "").split(";", 1)[0].strip() != "application/json":
|
||||
raise Failure(415, "json_required")
|
||||
try:
|
||||
length = int(environ.get("CONTENT_LENGTH", ""))
|
||||
except ValueError:
|
||||
raise Failure(411, "length_required") from None
|
||||
if not 0 < length <= MAX_BODY:
|
||||
raise Failure(413, "body_too_large")
|
||||
if not self.slot.acquire(blocking=False):
|
||||
raise Failure(429, "busy")
|
||||
try:
|
||||
raw = environ["wsgi.input"].read(length)
|
||||
if len(raw) != length:
|
||||
raise Failure(400, "incomplete_body")
|
||||
try:
|
||||
data = validate_request(json.loads(raw))
|
||||
except (ValueError, UnicodeError):
|
||||
raise Failure(400, "invalid_json") from None
|
||||
result = self.engine.embed(data)
|
||||
finally:
|
||||
self.slot.release()
|
||||
return self.response(start_response, 200, result)
|
||||
except Failure as error:
|
||||
return self.response(start_response, error.status, {"error": error.code})
|
||||
except Exception:
|
||||
logging.error("ML operation failed (internal_error)")
|
||||
return self.response(start_response, 500, {"error": "internal_error"})
|
||||
|
||||
@staticmethod
|
||||
def response(start_response, status, data):
|
||||
from http import HTTPStatus
|
||||
body = json.dumps(data, allow_nan=False, separators=(",", ":")).encode()
|
||||
headers = [("Content-Type", "application/json"), ("Content-Length", str(len(body))), ("Cache-Control", "no-store")]
|
||||
if status == 429:
|
||||
headers.append(("Retry-After", "5"))
|
||||
start_response(f"{status} {HTTPStatus(status).phrase}", headers)
|
||||
return [body]
|
||||
|
||||
|
||||
def create_app():
|
||||
token = Path(os.environ["PAGES_ML_TOKEN_FILE"]).read_text().strip()
|
||||
enabled = os.getenv("PAGES_ML_ALLOW_OPENAI", "false") == "true"
|
||||
key_file = os.getenv("PAGES_ML_OPENAI_KEY_FILE", "")
|
||||
key = Path(key_file).read_text().strip() if enabled and key_file else ""
|
||||
if enabled and not key:
|
||||
raise ValueError("OpenAI enabled but no key file configured")
|
||||
return Application(token, Engine(os.getenv("PAGES_ML_MODEL_DIR", "/models"), enabled, key))
|
||||
@@ -0,0 +1,7 @@
|
||||
gensim==4.4.0
|
||||
gunicorn==27.0.1
|
||||
numpy==2.2.6
|
||||
scipy==1.15.3
|
||||
smart_open==7.3.0.post1
|
||||
wrapt==1.17.3
|
||||
packaging==25.0
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Synthetic training -> Gunicorn HTTP -> Go client. No Docker or paid API.
|
||||
|
||||
Run using the same pinned dependencies as the service. All artifacts are placed
|
||||
in a temporary directory and removed on exit. Requires localhost listening.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
from train import train
|
||||
|
||||
DOMAIN = "11111111-1111-4111-8111-111111111111"
|
||||
SCOPE = "22222222-2222-4222-8222-222222222222"
|
||||
|
||||
|
||||
def main():
|
||||
service = Path(__file__).resolve().parent
|
||||
with tempfile.TemporaryDirectory(prefix="pages-ml-smoke-") as root:
|
||||
root = Path(root)
|
||||
source = root / "fixture.jsonl"
|
||||
source.write_text("\n".join(json.dumps({"text": t}) for t in [
|
||||
"合成文書 library books reading", "図書館 本 library books documents",
|
||||
"network server routing 文書", "サーバー network server machines"]))
|
||||
manifest = train(source, root / "models", DOMAIN, SCOPE, 8)
|
||||
token_path = root / "token"
|
||||
token_path.write_text("t" * 40)
|
||||
token_path.chmod(0o600)
|
||||
env = dict(os.environ, PAGES_ML_TOKEN_FILE=str(token_path),
|
||||
PAGES_ML_MODEL_DIR=str(root / "models"), PAGES_ML_ALLOW_OPENAI="false")
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0)); sock.listen()
|
||||
origin = "http://127.0.0.1:" + str(sock.getsockname()[1])
|
||||
process = subprocess.Popen([
|
||||
sys.executable, "-m", "gunicorn", "--bind", f"fd://{sock.fileno()}",
|
||||
"--workers", "1", "--worker-class", "gthread", "--threads", "2",
|
||||
"--timeout", "60", "--no-control-socket", "pages_ml:create_app()"],
|
||||
pass_fds=(sock.fileno(),), cwd=service, env=env)
|
||||
try:
|
||||
deadline = time.monotonic() + 15
|
||||
while True:
|
||||
if process.poll() is not None:
|
||||
raise RuntimeError("ML service exited before readiness")
|
||||
try:
|
||||
with urllib.request.urlopen(origin + "/healthz", timeout=1) as response:
|
||||
if json.load(response)["protocol"] == "1":
|
||||
break
|
||||
except OSError:
|
||||
pass
|
||||
if time.monotonic() > deadline:
|
||||
raise RuntimeError("ML service did not become ready")
|
||||
time.sleep(0.1)
|
||||
env.update(PAGES_ML_TEST_ORIGIN=origin, PAGES_ML_TEST_MODEL=manifest["model_sha256"])
|
||||
subprocess.run(["go", "test", "./internal/machinelearning", "-run", "TestLocalDoc2VecService", "-count=1", "-v"],
|
||||
cwd=service.parent.parent, env=env, check=True, timeout=120)
|
||||
print("Synthetic Doc2Vec -> HTTP -> Go client: PASS")
|
||||
finally:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill(); process.wait()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,141 @@
|
||||
import copy
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
import urllib.error
|
||||
|
||||
from pages_ml import Application, Engine, Failure, MAX_BODY, digest, tokens, validate_vectors
|
||||
from train import train
|
||||
|
||||
DOMAIN = "11111111-1111-4111-8111-111111111111"
|
||||
SCOPE = "22222222-2222-4222-8222-222222222222"
|
||||
TOKEN = "t" * 40
|
||||
|
||||
|
||||
def request():
|
||||
return {"protocol": "1", "domain_uuid": DOMAIN, "scope_uuid": SCOPE,
|
||||
"provider": "openai", "model": "text-embedding-3-small", "dimensions": 2,
|
||||
"inputs": [{"id": "page:chunk0", "text": "合成文書 library books"}], "allow_external": True}
|
||||
|
||||
|
||||
def call(app, data=None, **changes):
|
||||
body = json.dumps(data if data is not None else request()).encode()
|
||||
env = {"PATH_INFO": "/v1/embeddings", "REQUEST_METHOD": "POST", "CONTENT_TYPE": "application/json",
|
||||
"CONTENT_LENGTH": str(len(body)), "HTTP_AUTHORIZATION": "Bearer " + TOKEN, "wsgi.input": io.BytesIO(body)}
|
||||
env.update(changes)
|
||||
result = []
|
||||
raw = b"".join(app(env, lambda status, headers: result.extend([int(status.split()[0]), dict(headers)])))
|
||||
return result[0], json.loads(raw), result[1]
|
||||
|
||||
|
||||
class BoundaryTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.engine = Engine("/nonexistent")
|
||||
self.app = Application(TOKEN, self.engine)
|
||||
|
||||
def test_auth_and_health(self):
|
||||
for value in ("", "Bearer wrong", "Bearer ü"):
|
||||
self.assertEqual(call(self.app, HTTP_AUTHORIZATION=value)[0], 401)
|
||||
self.assertEqual(call(self.app, PATH_INFO="/healthz", REQUEST_METHOD="GET", HTTP_AUTHORIZATION="")[0], 200)
|
||||
self.assertEqual(call(self.app, PATH_INFO="/healthz?token=secret")[0], 404)
|
||||
with self.assertRaises(ValueError):
|
||||
Application("short", self.engine)
|
||||
|
||||
def test_external_off_without_network(self):
|
||||
with patch("urllib.request.build_opener") as opener:
|
||||
self.assertEqual(call(self.app)[0], 403)
|
||||
self.engine.external_enabled, self.engine.api_key = True, "fake-key"
|
||||
data = request(); data["allow_external"] = False
|
||||
self.assertEqual(call(self.app, data)[0], 403)
|
||||
opener.assert_not_called()
|
||||
|
||||
def test_bounds_and_busy(self):
|
||||
for changes, status in [({"CONTENT_LENGTH": str(MAX_BODY+1)}, 413),
|
||||
({"CONTENT_LENGTH": ""}, 411), ({"CONTENT_TYPE": "text/plain"}, 415),
|
||||
({"wsgi.input": io.BytesIO(b"{")}, 400)]:
|
||||
self.assertEqual(call(self.app, **changes)[0], status)
|
||||
for key, value in [("scope_uuid", "../../"), ("dimensions", True), ("dimensions", 1537),
|
||||
("inputs", []), ("inputs", [{"id": "a", "text": "x"*6001}]),
|
||||
("allow_external", "true"), ("unexpected", "x")]:
|
||||
data = request(); data[key] = value
|
||||
self.assertEqual(call(self.app, data)[0], 400)
|
||||
data = request(); data["inputs"] *= 2
|
||||
self.assertEqual(call(self.app, data)[0], 400)
|
||||
self.app.slot.acquire()
|
||||
try:
|
||||
status, _, headers = call(self.app)
|
||||
self.assertEqual(status, 429); self.assertEqual(headers["Retry-After"], "5")
|
||||
self.assertEqual(call(self.app, PATH_INFO="/healthz", REQUEST_METHOD="GET")[0], 200)
|
||||
finally:
|
||||
self.app.slot.release()
|
||||
|
||||
def test_openai_contract(self):
|
||||
self.engine.external_enabled, self.engine.api_key = True, "fake-key"
|
||||
data = request()
|
||||
result = {"model": data["model"], "data": [{"index": 0, "embedding": [0.5, -0.2]}], "usage": {"total_tokens": 10}}
|
||||
with patch("urllib.request.build_opener") as opener:
|
||||
opener.return_value.open.return_value.__enter__.return_value.read.return_value = json.dumps(result).encode()
|
||||
status, body, _ = call(self.app, data)
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(body["outputs"][0]["input_sha256"], digest(data["inputs"][0]["text"].encode()))
|
||||
sent = opener.return_value.open.call_args.args[0]
|
||||
self.assertEqual(sent.full_url, "https://api.openai.com/v1/embeddings")
|
||||
self.assertEqual(json.loads(sent.data)["encoding_format"], "float")
|
||||
result["data"][0]["embedding"] = [float("nan"), 1]
|
||||
opener.return_value.open.return_value.__enter__.return_value.read.return_value = json.dumps(result).encode()
|
||||
self.assertEqual(call(self.app)[0], 502)
|
||||
opener.return_value.open.side_effect = urllib.error.HTTPError(sent.full_url, 429, "secret input", {}, io.BytesIO(b"secret"))
|
||||
status, body, _ = call(self.app)
|
||||
self.assertEqual(status, 429); self.assertNotIn("secret", json.dumps(body))
|
||||
# No automatic provider retries.
|
||||
self.assertEqual(opener.return_value.open.call_count, 3)
|
||||
|
||||
def test_bad_vectors_and_tokenizer(self):
|
||||
for vectors in ([[0, 0]], [[1]], [[True, 1]], [[float("inf"), 1]], [[10**1000, 1]], []):
|
||||
with self.assertRaises(Failure): validate_vectors(vectors, 1, 2)
|
||||
self.assertEqual(tokens("図書館 BOOK"), ["図書", "書館", "book"])
|
||||
|
||||
|
||||
class Doc2VecTests(unittest.TestCase):
|
||||
def test_real_train_infer_and_isolation(self):
|
||||
# Only generated fixture text, never data/ or user documents.
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
source = Path(root) / "synthetic.jsonl"
|
||||
source.write_text("\n".join(json.dumps({"text": text}) for text in [
|
||||
"図書館 読書 本 library books reading", "図書館 本 文書 library documents books",
|
||||
"ネットワーク サーバー network server routing", "サーバー 通信 network routing server"]))
|
||||
manifest = train(source, root, DOMAIN, SCOPE, 8)
|
||||
engine = Engine(root); app = Application(TOKEN, engine)
|
||||
data = request(); data.update(provider="doc2vec", model=manifest["model_sha256"], dimensions=8, allow_external=False)
|
||||
status, result, _ = call(app, data)
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(len(result["outputs"][0]["vector"]), 8)
|
||||
self.assertEqual(call(app, data)[1]["outputs"], result["outputs"])
|
||||
for key in ("domain_uuid", "scope_uuid"):
|
||||
other = copy.deepcopy(data); other[key] = "33333333-3333-4333-8333-333333333333"
|
||||
self.assertEqual(call(app, other)[0], 404)
|
||||
unknown = copy.deepcopy(data); unknown["inputs"][0]["text"] = "zzzzunknownword"
|
||||
self.assertEqual(call(app, unknown)[0], 422)
|
||||
wrong = copy.deepcopy(data); wrong["dimensions"] = 9
|
||||
self.assertEqual(call(app, wrong)[0], 409)
|
||||
model_dir = Path(root) / DOMAIN / SCOPE / data["model"]
|
||||
model_file = model_dir / "model.bin"
|
||||
original = model_file.read_bytes()
|
||||
model_file.write_bytes(b"untrusted replacement")
|
||||
self.assertEqual(call(app, data)[0], 409)
|
||||
model_file.write_bytes(original)
|
||||
self.assertEqual(call(app, data)[0], 200)
|
||||
model_file.unlink()
|
||||
self.assertEqual(call(app, data)[0], 404)
|
||||
model_file.write_bytes(original)
|
||||
self.assertEqual(call(app, data)[0], 200)
|
||||
(model_dir / "manifest.json").unlink()
|
||||
self.assertEqual(call(app, data)[0], 404) # Cached model cannot outlive removal.
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Offline operator-only Doc2Vec training. Never called by the HTTP API."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import tempfile
|
||||
|
||||
from pages_ml import TOKENIZER, MAX_TEXT_BYTES, digest, tokens, valid_uuid
|
||||
|
||||
|
||||
def train(source, root, domain, scope, dimensions=128):
|
||||
if not valid_uuid(domain) or not valid_uuid(scope) or not 1 <= dimensions <= 1536:
|
||||
raise ValueError("invalid scope or dimensions")
|
||||
if os.getenv("PYTHONHASHSEED") != "0":
|
||||
raise ValueError("set PYTHONHASHSEED=0 before starting training")
|
||||
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
|
||||
docs, hashes, total_bytes = [], [], 0
|
||||
# Export permission and cohort membership must be checked by Pages/operator.
|
||||
# No URLs or paths inside the corpus are followed.
|
||||
with open(source, "rb") as stream:
|
||||
while line := stream.readline(65537):
|
||||
total_bytes += len(line)
|
||||
if len(line) > 65536 or total_bytes > 16 * 1024 * 1024 or len(docs) >= 10000:
|
||||
raise ValueError("corpus exceeds pilot limits")
|
||||
item = json.loads(line)
|
||||
if not isinstance(item, dict) or set(item) != {"text"} or not isinstance(item["text"], str):
|
||||
raise ValueError("expected JSONL records with text only")
|
||||
text = item["text"]
|
||||
if not text.strip() or len(text.encode()) > MAX_TEXT_BYTES:
|
||||
raise ValueError("empty or oversized document")
|
||||
words = tokens(text)
|
||||
if not words:
|
||||
raise ValueError("no tokens")
|
||||
docs.append(TaggedDocument(words, [str(len(docs))]))
|
||||
hashes.append(digest(text.encode()))
|
||||
if len(docs) < 2:
|
||||
raise ValueError("at least two documents required; this does not guarantee model quality")
|
||||
model = Doc2Vec(documents=docs, vector_size=dimensions, dm=0, workers=1,
|
||||
epochs=40, min_count=1, seed=0)
|
||||
parent = Path(root) / domain / scope
|
||||
parent.mkdir(parents=True, exist_ok=True)
|
||||
temp = Path(tempfile.mkdtemp(prefix=".training-", dir=parent))
|
||||
try:
|
||||
model.save(str(temp / "model.bin"), separately=[])
|
||||
model_hash = digest((temp / "model.bin").read_bytes())
|
||||
manifest = {"domain_uuid": domain, "scope_uuid": scope, "dimensions": dimensions,
|
||||
"tokenizer": TOKENIZER, "model_sha256": model_hash,
|
||||
"corpus_sha256": digest("\n".join(hashes).encode()), "documents": len(docs),
|
||||
"algorithm": "pv-dbow", "epochs": 40, "gensim": "4.4.0", "seed": 0, "workers": 1}
|
||||
(temp / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
|
||||
# Never replace an existing generation in place.
|
||||
temp.rename(parent / model_hash)
|
||||
return manifest
|
||||
finally:
|
||||
if temp.exists():
|
||||
shutil.rmtree(temp)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("source", help="Authorized JSONL corpus, one text record per line")
|
||||
parser.add_argument("--model-dir", required=True)
|
||||
parser.add_argument("--domain", required=True)
|
||||
parser.add_argument("--scope", required=True, help="UUID identifying one authorized learning cohort")
|
||||
parser.add_argument("--dimensions", type=int, default=128)
|
||||
args = parser.parse_args()
|
||||
print(json.dumps(train(args.source, args.model_dir, args.domain, args.scope, args.dimensions)))
|
||||
Reference in new issue
Block a user