Changelog¶
Unreleased¶
Added¶
clef tune(ROCm, TunableOp on by default): tunes the GEMM shapes the server served untuned after warmup (recorded in<state dir>/tunableop/<model>@<rev8>/tunableop_untuned0.csv) and adds them to the tuned file.- Self-evolving router and Review queue (E2):
PUT|GET|DELETE /v1/routers/{name},POST .../route[/batch],.../propose,.../versions[/{v}/activate],GET /v1/review,POST /v1/review/{id}/resolve. A router buffers what its classifier cannot place ("other", or below a threshold that rises with the label count), sends 20 items at a time to an LLM for new labels, re-classifies them with clef against the proposed set before accepting, and only adds labels (at most 63 plusother). Review mode (default) queues proposals; auto mode publishes them as a new classifier version. Cold start proposes a starter set from the first 20 items. Off unlessGEMINI_API_KEY(orCLEF_LLM_API_KEY) is set;CLEF_LLM_BASE_URL/CLEF_LLM_MODELpoint it at ollama, LM Studio or OpenAI. NewCLEF_ROUTER_*,CLEF_LLM_*andCLEF_REVIEW_TTL_DAYSsettings,docs/router.md, a console Review screen, router and review helpers in the Python and JS clients, and an LLM line inclef doctor. - Saved classifiers accept
review_threshold(single-label): interactive runs below it, by the classifier's owner or an admin, are queued for review (another key's runs are never captured, so its text does not reach the owner). Review input text is dropped when resolved, when an item becomespermanent_other, and afterCLEF_REVIEW_TTL_DAYS(30). - Job scheduler (E1): up to
CLEF_JOB_ACTIVE(default 4) jobs run in turns, one chunk in flight across all of them, so interactive requests keep their priority.POST /v1/jobstakespriority(low|normal|high; strict classes, aging withCLEF_JOB_AGING_S),urgent(newurgentscope: top class, ignores the window),schedule({"window": "20:00-06:00", "tz": ...}orCLEF_JOB_WINDOW/CLEF_JOB_TZ; a job that leaves its window staysrunningwithwaiting_reason: "off_hours"; a window that lies entirely in a daylight-saving gap does not open that day) andexpire_after_s(counted from when the window opens; endscancelledwitherror: "expired"). Turns are shared fairly per key (stride scheduling; a key whose jobs sat out a window or waited for a slot starts level with the others when they resume, it does not bank the missed turns), and so are slots: when another key waits, a key holding more thanceil(CLEF_JOB_ACTIVE / keys wanting a slot)lets its newest job wait (running,active_limit) after its current chunk. Job objects gainpriority,urgent,schedule,waiting_reason,next_window_at,expired,model,tokens;GET /v1/jobs?priority=. The daily record quota is reserved at submit (UTC day of the submit, refunded for what a cancelled / failed / expired job did not process); result-cache hits are not charged (counted in the newjobs.hitscolumn, migration0003, so the refund is exact after a restart). Python API:JobRunner.submit/cancel/get,JobHandle.decide, and the kind keyscompleted_if_all_failed(a run where every item failed still endssucceeded) andrecords(quota size). New dependencytzdata(server extra). .envfiles: clef loadsKEY=VALUElines from./.envand then~/.config/clef/envbefore reading its settings, soGEMINI_API_KEY=...can live in a file next to where you runclef serve. A variable already set (non-empty) in the environment always wins;CLEF_ENV_FILE=<path>loads only that file andCLEF_ENV_FILE=loads none (read from the real environment only, never from a file). OnlyCLEF_*andGEMINI_API_KEYare taken from files; other names are ignored with a warning. Values are never logged; the server logs the loaded file names at startup andclef doctorlists them. See docs/configuration.md.- Job throughput flags (F2, off by default):
CLEF_JOB_SORT_WINDOW=Nsorts each window of N job items by token length before they reach the engine, andCLEF_TOKENIZE_AHEAD=1encodes the next window on CPU threads while the current one is on the GPU. Results stay in input order, rows stay gap-free and a resume recomputes at most one window. Applies to the classify, score, systemone, evaluate and batch (OpenAI Batches, F1) job kinds. Measured on the 7900 XTX: the sort window gave +13-14% job throughput but a worse interactive p95 (926 ms), and tokenize ahead gained nothing, so both stay off by default (see docs/performance.md). - OpenAI Files and Batches (F1):
POST/GET/DELETE /v1/files(multipart upload of.jsonl,purpose=batch,/contentstreamed) andPOST/GET /v1/batches,POST /v1/batches/{id}/cancel, for chat completions,/v1/classifyand/v1/scorelines. TheopenaiSDK'sclient.files/client.batcheswork unchanged; errors use the OpenAI shape. A batch is one job of kindbatch(GET /v1/jobs?kind=batch), so it shares the queue, quota, resume and retention; output and error files are streamed from the job's rows, not stored. Private to the key that created them, scopejobs. New:CLEF_MAX_FILE_MB(200, body limit ofPOST /v1/filesonly),CLEF_MAX_BATCH_LINES(50000),CLEF_FILE_TTL_HOURS(720); newserverdependencypython-multipart. Theclefextension (extra_body={"clef": {"priority", "urgent", "schedule"}}) goes to the job scheduler, andexpires_atis 24 h after the batch could first run. Jobs gainjobs.tokens(the sum of the rows'input_tokens) and result rows with a 4xxstatus_codeno longer trip the circuit breaker.POST /v1/jobswithkind: "batch"runs the same structural check of the input file at submit (400 naming the first bad line); a line nested too deeply to parse is aninvalid_json_line, not a 500. See docs/openai-compat.md. bench/vllm/(Wave G, run on the 7900 XTX: vLLM is +10% at concurrency 8-32 but slower for single requests, so it is not adopted):vllm_check.shbenchmarks a pinned vLLM ROCm nightly container against clef (flags off, and MASK_FREE + FAST_HEAD) with a parity run, load at concurrency 1/8/16/32 and an adopt / do-not-adopt table; A refused run touches nothing, and cleanup removes only the container id and clef state dirs of its own run (bench/out/vllm/run-*); an unreadable GPU needsFORCE=1.vllm_client.pymaps clef records to vLLM's/v1/systemoneand fails loudly on a shape mismatch.clef bench's load generator takes an optional response check.GET /readyz(open): 200{"ready": true}only when the model is ready and the server is not draining, else 503 withstatusloading|warming|error|draining. WithCLEF_DRAIN_S=N(clef serve --drain-s N, default 0) the first SIGTERM / Ctrl-C keeps the server up for N seconds answeringdraining(a second signal stops at once), so a load balancer stops routing first; e.g.5behind a load balancer, below Docker's 10 s stop timeout. The Docker images and compose file now health-check/readyz(start period 600 s), so a container whose model failed to load is reported unhealthy;/livezstays the process-up probe.CLEF_LOG_FORMAT=json(clef serve --log-format json): app, uvicorn and access log lines as one JSON object per line (ts,level,logger,msg,request_id). The defaulttextoutput is unchanged.- Database layer (C1): jobs, saved classifiers and an audit log now live in one database: SQLite
<state_dir>/clef.dbby default, or Postgres withCLEF_DATABASE_URL=postgresql://...(pip install 'clef-local[postgres]'; one clef server per database, enforced with an advisory lock). SQLAlchemy Core + Alembic (newserverdependencies); every start migrates the schema. On the first startjobs.dbis copied toclef.db(online backup API; the original becomesjobs.db.migrated, and ajobs.dbstill open in a running v3.1 server stops the start untouched) and theclassifiers/*.jsonfiles are imported once (the folder becomesclassifiers.imported/). New commands:clef db current|upgrade|copy(copy SQLite to Postgres),clef backup(SQLite online backup, safe while serving),clef classifiers export.clef doctorchecks the schema and/healthhas adbblock. A database that cannot be reached answers503 database unavailable. Therequirements/*.txtlocks (and so the Docker images) now include sqlalchemy, alembic and thepostgresextra (psycopg 3). - Versioned saved classifiers with an owner: every
PUT /v1/classifiers/{name}that changes the definition adds a version (an identical PUT is a no-op);GET ?version=N,GET /v1/classifiers/{name}/versions[/{v}]; runs, jobs andPOST /v1/evaluateaccept"version", and job snapshots recordclassifier_version. The first PUT's key owns the classifier: once per-key principals exist (v3.2 keys), only the owner or an admin may change or delete it. - Jobs record the model they were submitted for (
jobs.model) and fail clearly when the server now serves another one; a payloadmodelthis server does not serve is404at submit. - Decision models (C2):
CLEF_MODEL=<id>[@<revision>]picks the served model from a catalog (clef models):clef-flash(default) orclef, the 27B (Cloudflare/clef@0b331204, ~55 GB; fits a 24 GB GPU only withCLEF_QUANT=nf4,clef doctorwarns).clef download --model cleffetches it. Models come from adapters registered under theclef.modelsentry-point group, so a third-party package can add its own;CLEF_MODEL_PATH/_REPO/_REVISIONkeep working./healthand/v1/modelsreport the served model (adapter, revision, capabilities).Cache-Control: no-cacheon an inference request will bypass the result cache (once it lands). - Keys and principals (D1): managed API keys (
clef keys create|list|rotate|revoke|update|usage, the console Keys tab,/v1/admin/keys*): a principal has scopes (classify,jobs,classifiers,ops,admin,urgent; a missing one is403), an optional daily record quota (429+Retry-After,X-Quota-Limit/X-Quota-Remaining; cache hits are free, a job is charged at submit and refunded for what it did not run), a per-key rate limit, expiry, revocation and rotation with a 24 h grace. Keys areclef_live_<id>_<secret>and only their SHA-256 is stored.CLEF_API_KEY/CLEF_API_KEYSstay as full-admin break-glass keys; auth turns on with the first of either and never turns off by itself./v1/admin/*always needs an admin key.GET /v1/whoami; admins see every job;GET /v1/admin/auditlists key, job and classifier changes; classifier owners are now enforced. Env keys can see each other's jobs (they are admins). Moved: the "listening on a non-loopback address without a key" warning is logged at server start (it needs the database to know about managed keys).
Upgrade notes¶
- Several env keys are all admin. Before D1,
CLEF_API_KEYS=alice:..,bob:..meant per-key job and classifier ownership. Now every env key is a full admin (decision D10, deliberate): each env key can see, cancel and delete every job and read its results, edit and delete every saved classifier, mint and revoke managed keys and read the audit log. Nothing breaks on upgrade, but the isolation between those keys is gone. The server logs a WARNING at startup when it sees more than one env key. For separate tenants, create one managed key per tenant (clef keys create NAME --scope classify,jobs) and keep a single env key as the operator's break-glass key. - Names must not clash. A managed key named like an env key (for example
ciinCLEF_API_KEYS=ci:..) is refused with401and a startup warning; runclef keys revoke cior rename the env key. - Owner-less data. Jobs and classifiers created while auth was off (owner NULL) become admin-only to modify or delete once auth is on; reading the results of an owner-less job is admin-only too. Non-admin keys can still run owner-less classifiers.
Changed¶
- TunableOp tunes in the background (
CLEF_TUNABLEOP, now on by default on ROCm). A live request never tunes any more (it used to stall for seconds on every new shape: measured p50 2.7 s, p95 39 s). The server is ready after the normal warmup; it records the GEMMs of every text-batch shape up to 1024 tokens and a separate tuner process (python -m clef_server.tuner) tunes them one at a time, paused while requests arrive; the server reloads each result as it lands. About an hour of idle time on the 7900 XTX, once per GPU / driver / ROCm / torch version. Measured gain once tuned: +27-32% req/s on mixed-length traffic, single requests p50 104 vs 137 ms. Progress in/v1/stats(tunableop).CLEF_TUNABLEOP=0turns it off;CLEF_TUNABLEOP_ONLINE=1keeps the old behaviour. CLEF_MASK_FREEandCLEF_FAST_HEADdefault to on with the ROCm backend (unset = auto; off on CUDA, MPS and CPU until measured there;0/1forces them). Bench baselines set all three to 0 explicitly.modelin requests: optional everywhere (omit it, or send null, for the served model); responses report the served id. A model the server does not serve is now 404 on every route (OpenAI routes:model_not_found) instead of being ignored;/v1/chat/completionsno longer listsmodelinclef.ignored. The Hugging Face path id (/hf/models/{id}) is still ignored. The Python and JS clients and the console no longer sendmodel: "clef-flash". A/v1/systemonechoice / score question with more thanCLEF_MAX_LABELSoptions is now a 400.- TunableOp results are per model (
CLEF_TUNABLEOP=1, ROCm): they now live in<state dir>/tunableop/<model id>@<rev8>/, so the first ROCm start after upgrading tunes again (a few minutes); the old<state dir>/tunableop_*.csvfiles are no longer read and can be deleted.
Fixed¶
- Console live stream: a CRLF split across two network chunks was read as a blank line, which could split one
server-sent event in two. A trailing
\ris now held back until the next chunk. - Lost cancel: a cancel that raced a runner error could be dropped (the job was parked
interruptedjust before the cancel flag was written, which only matchedrunningjobs) and the job was later resumed. Aninterruptedjob is now cancelled at once, with itsjob.cancelledevent, in one transaction. - API key in the access log: the uvicorn access log wrote
/v1/events?key=<key>(the console's live stream), so the key ended up inclef.log. Thekey,api_keyandtokenquery values are now logged asREDACTED(names are percent-decoded first, as auth reads them, and matched case-insensitively, so?k%65y=is masked too), and the console reads the stream withfetch()and theX-API-Keyheader.?key=still works for other clients. SECURITY.md has Caddy / nginx snippets for masking keys in proxy logs. - CUDA install:
accelerateandtorchvisionare now declared in thecudaextra and pinned inrequirements/cuda.txt(the model code imports both, and loading crashed without them). The uv commands for the CUDA lock use--index-strategy unsafe-best-match, because uv otherwise reports the pinnedcertifias unsatisfiable. bench/*.pyfind the weights in the Hugging Face cache likeclef servedoes, instead of requiring--model-path.
Validated¶
- CUDA on hardware (RTX 4070 Ti 12 GB, WSL2, torch 2.11.0+cu128): smoke test, serving,
pytest -m gpu(22 passed with torchao),clef benchandbench/memory_bench.pyin the int8 and CPU-offload modes. Numbers indocs/hardware-results.md.CLEF_PAD_MULTIPLE8 was ~12% faster than the default 64 at concurrency 8 on this card (default unchanged).causal-conv1d(built from source) made no measurable difference (1.6%, within noise).nf4matches the ROCm run (36 of 399 flips, still not recommended). Plain bf16 and native Ubuntu are still untested. - LangChain (
langchain-openai1.7.1):with_structured_outputworks with thejson_schemaandfunction_callingmethods against the compat routes;json_modeand plain chat return the documented400 missing_schema. - On CUDA, int8 with torchao is more accurate and faster than the default bitsandbytes (mean error 0.0057 against
0.0172; 3 against 22 flipped answers of 399; p50 170 against 232 ms). The default is unchanged; see
docs/memory.md.
3.1.0 (2026-10-04)¶
Four features on top of 3.0.0, plus the public-release sweep. Everything was run on the verified Windows + WSL2 +
ROCm setup (RX 7900 XTX): the compat routes with the official openai and huggingface_hub SDKs, evaluation on
examples/tickets_labelled.csv (accuracy 0.87, ECE 0.04), a 500-item job alongside interactive traffic, and every
memory mode. CUDA and Apple Silicon remain untested on hardware.
Added¶
- OpenAI and Hugging Face compatibility (guide):
GET /v1/models[/{id}]andPOST /v1/chat/completionsturn a JSON schema (response_formator one forced tool) into decisions: string enum -> choice, boolean -> yes/no, integer enum / bounded integer /x-clef-ordinalstring enum -> score, array of string enums -> multi-label. Answers are argmax JSON inmessage.content, withlogprobs(log of the calibrated probability), a non-standardcleffield with every probability, streaming (SSE) and OpenAI-shaped errors. A request without a usable schema is a400 missing_schema.POST /hf/models/{id}is the Hugging Face zero-shot endpoint (classic{sequence, labels, scores}or the[{label, score}]list thathuggingface_hub1.x expects). LangChain is not tested. - Evaluation (guide):
POST /v1/evaluate(labelled rows, optionally a saved classifier; up toCLEF_MAX_EVAL_ROWS, default 500) andPOST /v1/evaluate/metrics(scores you already have, no inference). Accuracy, top-2, macro / micro / weighted F1, per-label precision / recall / F1, confusion matrix, reliability bins, ECE, MCE, Brier, log-loss, a coverage-vs-accuracy curve andauto_routethresholds; multi-label reports exact match and Hamming loss. Anevaluatejob kind handles up toCLEF_MAX_JOB_EVAL_ROWS(100000) rows.examples/tickets_labelled.csvis a 47-ticket sample. - Console: Evaluate tab: upload CSV / JSON / JSONL, pick the input and gold columns, run with progress and cancel, then read the confusion heatmap, reliability diagram, coverage curve with a threshold readout, per-label table and mistakes list; export predictions or metrics.
- Async jobs and webhooks (guide):
POST /v1/jobs(kindsclassify,score,systemone,evaluate;202withLocation),GET /v1/jobs,GET /v1/jobs/{id},GET /v1/jobs/{id}/results(JSON pages, or?format=ndjson|csv),POST /v1/jobs/{id}/cancel,DELETE /v1/jobs/{id}. Jobs live in SQLite (<state dir>/jobs.db), run FIFO with one micro-batch in flight so interactive calls interleave, resume after a restart, and belong to the API key that submitted them. Webhooks (job.succeeded,job.failed,job.cancelled, opt-injob.progress) are signed withX-Clef-Signature: sha256=HMAC(secret, "<timestamp>.<body>")and are off untilCLEF_WEBHOOK_ALLOWlists the receivers. New settings:CLEF_MAX_JOB_ITEMS,CLEF_MAX_JOBS,CLEF_JOB_TTL_HOURS,CLEF_JOB_ENGINE_WAIT_S,CLEF_WEBHOOK_ALLOW,CLEF_WEBHOOK_TIMEOUT_S,CLEF_WEBHOOK_ATTEMPTS. - Clients: Python (
submit_job,classify_job,job,jobs,cancel_job,delete_job,wait_job,job_results,save_job_results; sync and async) and JavaScript (submitJob,classifyJob,job,jobs,cancelJob,deleteJob,waitJob,jobResults). Examples:openai_sdk.py,hf_zero_shot.py,jobs.py. - Smaller GPUs (guide):
CLEF_OFFLOAD=cpu(--offload) keeps the embeddings and any layers that do not fit in host RAM and streams them in per forward;CLEF_MAX_DEVICE_MEMORY_GB(--max-device-memory-gb) caps device memory as a hard allocator limit.CLEF_QUANT=int8now works on ROCm, Apple Silicon and CPU through torchao (CUDA keeps bitsandbytes);CLEF_QUANT_BACKEND=auto|bnb|torchaopicks the library.clef doctorprints a recommended memory setting. torchao is part of therocm,mps,cpuand newquantextras.bench/memory_bench.pyreproduces the measurements. - Extension point:
clef_server/appctx.pydefinesAppContext. A feature module exposesrouter(ctx) -> APIRouterand is listed inmain.FEATURES(evaluation,compat,jobs); the context carries config, stats, engine, auth and rate-limit dependencies, the inference helpers and startup / shutdown hooks. Evaluation, compat and jobs are built on it. - Docs site (MkDocs Material, built with
--strictand published to thegh-pagesbranch byscripts/publish_docs.sh): https://miguelcarrascob.github.io/clef/, with the interactive API reference generated fromopenapi.json.
Changed¶
- Measured on the RX 7900 XTX (see docs/memory.md): offload is bit-identical to bf16. A 16 GB
card runs with
CLEF_OFFLOAD=cpu CLEF_MAX_DEVICE_MEMORY_GB=15(p50 152 -> 175 ms), a 12 GB card withCLEF_QUANT=int8 CLEF_OFFLOAD=cpu(about 206 ms, mean probability error 0.006, 2 of 399 top choices flipped) and an 8 GB card with a cap of 7 (about 540 ms, ~15 GB of host RAM). The old advice for 16 GB cards (CLEF_QUANT=nf4with bitsandbytes) is replaced: nf4 flipped about 9% of top choices on ROCm and is not recommended. CUDA and Apple Silicon are untested on hardware. CLEF_QUANT=int8is no longer CUDA only (see above).pip install "clef-local[quant]"adds torchao anywhere.- API keys also protect the new
/hf/models/*routes (they live outside/v1)./healthlimitsgainsmax_job_itemsandwebhooks_enabled. - README restructured for the public release (hero GIF, usage sections for the OpenAI SDK, evaluation and jobs, measured memory options); the docs site gains pages for the four features.
/healthgains amemoryblock (offload mode, cap, quant and quant backend, layers / embeddings on the host, host and device weight GB), shown on the Ops screen when not the default. Load-time fallbacks and caveats (cap not enforced, offload fallback, unpinned host memory, nf4 on ROCm, int8 on MPS, cap above free memory) are listed in/healthwarnings, andclef doctorwarns for those combinations and below a 7 GB offload cap on WSL.- Console: at 560 px and below the top bar wraps into two rows with a scrolling tab strip (no horizontal page scroll at 375 px).
- Jobs: a job whose items all fail (or that trips the circuit breaker on a systemic error) ends
failedinstead ofsucceeded; the job view gainswarningsandwebhook.failed_deliveries, clients gainhas_errors. Saved classifiers are copied into the job at submit (snapshot_of) for every kind, includingevaluate. Jobs interrupted more thanCLEF_JOB_MAX_RESUMES(3) times are failed.POST /v1/jobshonoursIdempotency-Key. Webhooks retry for ~8 minutes by default (CLEF_WEBHOOK_ATTEMPTS10,CLEF_WEBHOOK_BACKOFF_S,CLEF_WEBHOOK_BACKOFF_CAP_S) and a failed delivery can be resent withPOST /v1/jobs/{id}/webhook/redeliver. - Evaluation: the
evaluatejob kind waits for the model, isolates bad rows (n_errors) and resumes; rows with NaN / non-numeric scores or none of the labels are rejected, defaulted or clipped scores are counted;POST /v1/evaluatecounts in stats and the request log. - Compat chat responses list ignored request fields in
clef.ignored. - Python and JS clients:
save_job_results(require_finished=True)writes atomically;jobs()exposestotal; the JS client no longer retries a job submission after it was sent (unless an idempotency key is given). - GitHub Actions workflows (CI, release, docs) and Dependabot are removed; GitHub Actions is disabled for the repository. The checks in CONTRIBUTING.md are run locally before a PR, and the docs are published by hand.
Fixed¶
- Server start with
CLEF_MAX_DEVICE_MEMORY_GBsegfaulted on ROCm / WSL2: GPU telemetry sampling raced torch's own device initialisation. The sampler now skips GPU telemetry while the model loads. - Blank
CLEF_*variables (WSLENV forwards unset Windows variables as empty strings) now mean "unset" instead of failing config validation. - CSV export no longer prefixes negative numbers with a quote, and an export of a running job keeps every column.
Security¶
- Webhook deliveries are an SSRF surface, so they are off by default and gated by
CLEF_WEBHOOK_ALLOW. The allow-list is checked at submit and again on every attempt, the host is resolved right then and the request is pinned to the checked address (no DNS rebinding), link-local (cloud metadata), multicast, unspecified and reserved addresses are always refused, redirects and environment proxies are ignored and API keys are never sent. Webhook secrets are stored in clear text injobs.db(HMAC needs them). - Webhook addresses that embed an IPv4 address (NAT64
64:ff9b::/96and64:ff9b:1::/48, 6to4, Teredo) are judged by that IPv4 address, and site-local / reserved IPv6 ranges are refused, so a translated address can no longer reach a private host. Redelivery reuses the stored URL and re-runs every check. - Job results exported as CSV neutralise spreadsheet formulas (text cells starting with
=,+,-or@). - Jobs are owned by the API key name that submitted them; other keys get
404. Job payloads and results are kept on disk until deleted or untilCLEF_JOB_TTL_HOURSexpires. THIRD_PARTY_NOTICESfor the vendored Preact, htm and uPlot console libraries (src/clef_server/static/vendor/THIRD_PARTY_NOTICES.md).
Known gaps¶
- Jobs are not counted in
/v1/statsor the request log, and there is no priority lane: interactive calls are ~4x slower while a large job runs (p50 109 -> 422 ms measured). The webhook TLS path was not tested against a real TLS server; LangChain was not tested against the compat routes; offload, torchao int8 and the device cap are untested on NVIDIA and Apple Silicon.
3.0.0¶
Cross-platform release: the model now runs on NVIDIA (CUDA), AMD (ROCm), Apple Silicon (MPS) and CPU. Only the
Windows + WSL2 + ROCm path has been run on real hardware; CUDA and MPS are unit-tested with mocked backends and marked
"untested on hardware" until docs/hardware-validation.md has been run. Quantization accuracy and latency are pending
hardware.
Added¶
- Backends (
clef_server/backend.py):CLEF_DEVICE=autodetects cuda, rocm, mps or cpu; per-backend dtype rules with warnings and fallbacks, memory stats, optional GPU telemetry (pynvml, amdsmi, rocm-smi), a preflight memory check before loading, andbackend,fast_pathandversionsin/health. CLEF_QUANT=int8|nf4(bitsandbytes, CUDA only, refused elsewhere) for 16 GB NVIDIA GPUs.clefCLI:serve(foreground or--detach, health-gated),stop,status,logs,doctor(--no-gpu,--smoke,--json),download(pinned, resumable, disk-space check),bench,open,version.- Classification API:
POST /v1/classify(single and multi-label),/v1/classify/batch,/v1/score, and saved classifiers (PUT|GET|DELETE /v1/classifiers/{name},POST /v1/classifiers/{name}[/batch]). Same engine and probabilities as/v1/systemone. - Clients: typed Python client (sync + async, retries on 503) and a dependency-free JavaScript/TypeScript client
(
clients/js);examples/;openapi.jsonexported from the app and checked in CI. - Remote access: named API keys (
CLEF_API_KEYS), per-key rate limit (CLEF_RATE_LIMIT, 429 +Retry-After), opt-in CORS (CLEF_CORS_ORIGINS), key names in/v1/logand/v1/stats, warning when binding a non-loopback host without keys. Docs:docs/remote-access.md(LAN setup, firewall, Caddy TLS). - Console: time-series charts, KPI tiles, histograms, Classify mode, redesigned light/dark theme.
GET /v1/stats/timeseriesand a livepointin the SSEstatsevent. - Packaging: installable package (
src/clef_server,src/clef_client), per-backend lock files (requirements/{rocm,cuda,cpu,macos}.txt), Dockerfiles for CUDA and ROCm, compose file, systemd/launchd/Task Scheduler service files. - CI/release: matrix on Ubuntu, macOS and Windows (ruff, unit tests, wheel build, CLI smoke from the wheel),
JS tests, shellcheck, build-only Docker jobs; a
v*tag attaches the wheel, sdist andopenapi.jsonto a GitHub Release. Nothing is published to PyPI, GHCR or npm. - Repo: Apache-2.0
LICENSE,CONTRIBUTING.md,SECURITY.md, issue and PR templates,docs/troubleshooting.md,docs/hardware-validation.md,docs/hardware-results.md,docs/classification.md.
Changed¶
CLEF_DEVICEdefaults toauto(wascuda);CLEF_DTYPEdefaults toauto(wasbfloat16).- ROCm/WSL-only environment (
HSA_*, AOTriton) is applied only when the torch build is ROCm; macOS setsPYTORCH_ENABLE_MPS_FALLBACK=1. - Model path resolution:
CLEF_MODEL_PATH, else~/models/clef-flashif it holds a release, else the pinned Hugging Face cache snapshot. The server never downloads; useclef download. - State (log, pidfile, saved classifiers) lives in a per-OS state directory (
CLEF_STATE_DIR). scripts/launch_server.shandclef.ps1are thin wrappers over the CLI (clef.ps1keeps the WSL keep-alive).- README rewritten with per-platform quick starts, a support matrix and a hardware table.
Removed¶
server/directory (moved tosrc/clef_server/),requirements/server.txt(replaced by per-backend locks).
Migration notes from 2.x¶
- Code moved from
server/tosrc/clef_server/;python server/main.pybecomesclef serve(clef serve --detachreplaceslaunch_server.sh start). Imports:clef_server.*instead ofserver.*. pip install -r requirements/server.txtbecomespip install -r requirements/<rocm|cuda|cpu|macos>.txtfollowed bypip install -e ".[server]".CLEF_LOG_DIRstill works as an alias forCLEF_STATE_DIR. The new default location per OS is~/.local/state/clef(Linux, same as before),~/Library/Application Support/clef(macOS) and%LOCALAPPDATA%\clef(Windows).- Set
CLEF_DEVICE=cudaexplicitly if you relied on the old default on an NVIDIA/ROCm machine and want an error instead of a fallback; withautoa ROCm build is reported asrocm. CLEF_API_KEYkeeps working (one key nameddefault). UseCLEF_API_KEYSfor several named keys.- Weights: if they are not at
~/models/clef-flashorCLEF_MODEL_PATH, runclef download.
2.0.0¶
Fixed¶
- Media sharding bug: v1 split a request's images/videos across several records and answered from the last shard only. All media of a request now goes into ONE record, so answers reflect every image and video.
Changed¶
- GPU serialization + micro-batching: exactly one worker thread touches the GPU; concurrent requests are
coalesced (
CLEF_MAX_MICROBATCH,CLEF_BATCH_WINDOW_MS). Media records run alone. Responses carrytiming(queue, forward, total, batch_size). - Length grouping + alignment + warmup: concurrent text records are grouped by length bucket, padded to a
multiple of 64 (
CLEF_PAD_MULTIPLE; aligned GEMMs are faster on RDNA3), and common shapes are warmed at startup in the background (CLEF_BUCKETS,CLEF_WARMUP). Single-record p50/p95 142/150 ms (v1: 162/222). - Security hardening: optional API key (
CLEF_API_KEY), loopback bind by default, body-size limit, SSRF-guarded opt-in URL fetching,media_kwargsno longer client-settable, generic 500s with request ids, no request state logged unlessCLEF_LOG_STATE=1. - Strict validation: pydantic schemas for every route, per-index errors in batches, caps on questions,
images, videos, pixels and frames. Uniform
{detail, request_id}errors andX-Request-ID. - Clef Console at
/: playground, live stats, request log (/v1/stats,/v1/log,/v1/events). /healthreportsready|warming|loading|errorplus GPU and limits; new/livez.
Ops / packaging¶
scripts/env.shsingle source of environment;launch_server.shwith pidfile, log rotation and start|stop|restart|status|logs;clef.ps1Windows wrapper; systemd user unit (deploy/).- Exact dependency pins (
requirements/), idempotent setup scripts with pinned model revision,doctor.py. - Benchmarks rewritten (warm every shape, forward vs end-to-end, proper percentiles);
http_bench.pyandprofile_forward.pyadded. clef_clientPython package, unit tests, live integration tests, CI (ruff, shellcheck, pytest), pyproject.- Removed
fix_cc.sh,fastpath.py,fla_check.py,gpu_check.pyand theserver/test_*scripts.
1.0.0¶
- Initial local deployment of clef-flash on RX 7900 XTX via WSL2 ROCm 7.2 (torch 2.11.0+rocm7.2,
transformers 5.10.2) behind a FastAPI SystemOne-compatible server (
/v1/systemone,/v1/batch,/health). - Verified text/JSON, image, video and batch requests; single-record median 162 ms, peak VRAM 19.6 GB.