Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions serving/clef-flash/server/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
.git
.pytest_cache
.ruff_cache
.venv
__pycache__
tests
23 changes: 23 additions & 0 deletions serving/clef-flash/server/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
FROM python:3.12-slim

ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1

WORKDIR /app

RUN pip install --no-cache-dir uv==0.9.5 \
&& useradd --create-home --uid 10001 clef

COPY pyproject.toml uv.lock README.md ./
RUN uv sync --frozen --no-dev --extra model --no-install-project

COPY src ./src
RUN uv sync --frozen --no-dev --extra model

ENV PATH="/app/.venv/bin:$PATH"

USER 10001

EXPOSE 8080

CMD ["uvicorn", "clef_server.app:app", "--host", "0.0.0.0", "--port", "8080", "--no-access-log"]
51 changes: 51 additions & 0 deletions serving/clef-flash/server/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# CLEF-Flash SystemOne server

This package serves the decision head released with
[`Cloudflare/clef-flash`](https://huggingface.co/Cloudflare/clef-flash). It
loads `joint_schema_model.py` from a local model snapshot and exposes the
Jev/SystemOne-compatible `POST /v1/systemone` endpoint. It does not use the
Qwen text-generation interface.

The model card currently specifies Python 3.12, PyTorch 2.11, and Transformers
5.10.2. This runtime uses the official PyTorch 2.11 CUDA 12.6 build to remain in
the CUDA 12 driver compatibility family. The full BF16 snapshot occupies about
19 GB and requires a CUDA GPU for the intended deployment. This first runtime
accepts text or JSON state; HTTP image decoding is outside the Tetris example
scope.

## Test without a model

Install only the server and development dependencies:

```sh
uv sync --group dev
uv run pytest
uv run ruff check .
uv run ruff format --check .
```

Tests inject a fake decision adapter and do not download model weights or use
CUDA.

## Run with CLEF-Flash

Download the complete model repository, including `joint_head.safetensors` and
`joint_schema_model.py`, then start the server with its path:

```sh
uv sync --extra model
MODEL_PATH=/path/to/clef-flash uv run uvicorn \
clef_server.app:app --host 0.0.0.0 --port 8080
```

`MODEL_PATH` defaults to `/mnt/models/clef-flash`, and `MODEL_DEVICE` defaults
to `cuda`.

The runtime provides the following probes:

- `GET /health/live` stays healthy while the model loads and returns `503`
after an irrecoverable load failure so the container can be restarted.
- `GET /health/ready` returns `200` only after the model has loaded.
- `GET /metrics` exposes bounded-cardinality Prometheus metrics for model
readiness and load time, request outcomes and latency, inference latency, and
requests in flight.
60 changes: 60 additions & 0 deletions serving/clef-flash/server/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
[project]
name = "clef-systemone-server"
version = "0.1.0"
description = "SystemOne HTTP runtime for Cloudflare CLEF-Flash"
readme = "README.md"
requires-python = ">=3.12,<3.13"
dependencies = [
"fastapi>=0.119,<1",
"prometheus-client>=0.23,<1",
"structlog>=25.4,<26",
"uvicorn[standard]>=0.37,<1",
]

[project.optional-dependencies]
model = [
"accelerate>=1.12,<2",
"huggingface-hub>=0.35,<2",
"pillow>=11.3,<12",
"safetensors>=0.6,<1",
"torch==2.11.0",
"torchvision==0.26.0",
"transformers==5.10.2",
]

[dependency-groups]
dev = [
"httpx>=0.28,<1",
"pytest>=8.4,<9",
"ruff>=0.13,<1",
]

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[tool.hatch.build.targets.wheel]
packages = ["src/clef_server"]

[tool.uv.sources]
torch = [
{ index = "pytorch-cu126", marker = "sys_platform == 'linux' and platform_machine == 'x86_64'" },
]
torchvision = [
{ index = "pytorch-cu126", marker = "sys_platform == 'linux' and platform_machine == 'x86_64'" },
]

[[tool.uv.index]]
name = "pytorch-cu126"
url = "https://download.pytorch.org/whl/cu126"
explicit = true

[tool.pytest.ini_options]
testpaths = ["tests"]

[tool.ruff]
line-length = 88
target-version = "py312"

[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B", "SIM"]
1 change: 1 addition & 0 deletions serving/clef-flash/server/src/clef_server/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""CLEF-Flash SystemOne serving runtime."""
72 changes: 72 additions & 0 deletions serving/clef-flash/server/src/clef_server/adapter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import importlib.util
import os
import sys
from collections.abc import Callable
from pathlib import Path
from types import ModuleType
from typing import Protocol, cast


class DecisionAdapter(Protocol):
model_name: str

def decide(self, request: dict[str, object]) -> dict[str, object]: ...


SystemOne = Callable[[object, object, dict[str, object]], dict[str, object]]


class ClefAdapter:
model_name = "clef-flash"

def __init__(
self,
model: object,
processor: object,
systemone: SystemOne,
) -> None:
self._model = model
self._processor = processor
self._systemone = systemone

@classmethod
def from_environment(cls) -> "ClefAdapter":
path = Path(os.environ.get("MODEL_PATH", "/mnt/models/clef-flash"))
device = os.environ.get("MODEL_DEVICE", "cuda")
return cls.load(path, device)

@classmethod
def load(cls, path: Path, device: str) -> "ClefAdapter":
if not path.is_dir():
raise RuntimeError("CLEF model directory does not exist")

module_path = path / "joint_schema_model.py"
if not module_path.is_file():
raise RuntimeError("CLEF joint schema module is missing")

module = _load_module(module_path)
loader = getattr(module, "load_release_model", None)
systemone = getattr(module, "systemone", None)
if not callable(loader) or not callable(systemone):
raise RuntimeError("CLEF joint schema module has an invalid interface")

model, processor = loader(path, device=device)
return cls(model, processor, cast(SystemOne, systemone))

def decide(self, request: dict[str, object]) -> dict[str, object]:
return self._systemone(self._model, self._processor, request)


def _load_module(path: Path) -> ModuleType:
spec = importlib.util.spec_from_file_location("clef_joint_schema_model", path)
if spec is None or spec.loader is None:
raise RuntimeError("Unable to load CLEF joint schema module")

module = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module
try:
spec.loader.exec_module(module)
except Exception:
sys.modules.pop(spec.name, None)
raise
return module
Loading