jbr-inference 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. jbr_inference-0.1.0/.github/workflows/ci-python.yml +27 -0
  2. jbr_inference-0.1.0/.github/workflows/gitleaks.yml +32 -0
  3. jbr_inference-0.1.0/.github/workflows/release.yml +205 -0
  4. jbr_inference-0.1.0/.gitignore +28 -0
  5. jbr_inference-0.1.0/.gitleaks.toml +6 -0
  6. jbr_inference-0.1.0/.trivyignore +41 -0
  7. jbr_inference-0.1.0/CHANGELOG.md +21 -0
  8. jbr_inference-0.1.0/EXTENDING.md +284 -0
  9. jbr_inference-0.1.0/LICENSE +202 -0
  10. jbr_inference-0.1.0/NOTICE +12 -0
  11. jbr_inference-0.1.0/PKG-INFO +121 -0
  12. jbr_inference-0.1.0/README.md +86 -0
  13. jbr_inference-0.1.0/SECURITY.md +21 -0
  14. jbr_inference-0.1.0/TROUBLESHOOTING.md +315 -0
  15. jbr_inference-0.1.0/docs/SERVING-SERVICE.md +282 -0
  16. jbr_inference-0.1.0/docs/bench/proofs/deactivate-2026-07-23.md +90 -0
  17. jbr_inference-0.1.0/docs/bench/proofs/download-2026-07-22.md +115 -0
  18. jbr_inference-0.1.0/docs/bench/proofs/gpu-2026-07-21.md +143 -0
  19. jbr_inference-0.1.0/docs/bench/proofs/npu-2026-07-21.md +245 -0
  20. jbr_inference-0.1.0/docs/bench/proofs/streaming-2026-07-22.md +104 -0
  21. jbr_inference-0.1.0/docs/bench/proofs/switch-2026-07-22.md +163 -0
  22. jbr_inference-0.1.0/docs/bench/results/2026-07-21.json +239 -0
  23. jbr_inference-0.1.0/docs/bench/results/2026-07-21.md +304 -0
  24. jbr_inference-0.1.0/docs/npu/SPIKE.md +214 -0
  25. jbr_inference-0.1.0/jbr_inference/__init__.py +1 -0
  26. jbr_inference-0.1.0/jbr_inference/backends/__init__.py +1 -0
  27. jbr_inference-0.1.0/jbr_inference/backends/gpu/README.md +170 -0
  28. jbr_inference-0.1.0/jbr_inference/backends/gpu/__init__.py +1 -0
  29. jbr_inference-0.1.0/jbr_inference/backends/gpu/adapter.py +163 -0
  30. jbr_inference-0.1.0/jbr_inference/backends/gpu/config.py +71 -0
  31. jbr_inference-0.1.0/jbr_inference/backends/gpu/lifecycle.py +231 -0
  32. jbr_inference-0.1.0/jbr_inference/backends/gpu/server.py +119 -0
  33. jbr_inference-0.1.0/jbr_inference/backends/npu/README.md +181 -0
  34. jbr_inference-0.1.0/jbr_inference/backends/npu/__init__.py +1 -0
  35. jbr_inference-0.1.0/jbr_inference/backends/npu/adapter.py +98 -0
  36. jbr_inference-0.1.0/jbr_inference/backends/npu/config.py +124 -0
  37. jbr_inference-0.1.0/jbr_inference/backends/npu/convert_model.py +92 -0
  38. jbr_inference-0.1.0/jbr_inference/backends/npu/inference.py +105 -0
  39. jbr_inference-0.1.0/jbr_inference/backends/npu/server.py +221 -0
  40. jbr_inference-0.1.0/jbr_inference/bench/README.md +153 -0
  41. jbr_inference-0.1.0/jbr_inference/bench/__init__.py +1 -0
  42. jbr_inference-0.1.0/jbr_inference/bench/runner.py +561 -0
  43. jbr_inference-0.1.0/jbr_inference/models/README.md +47 -0
  44. jbr_inference-0.1.0/jbr_inference/models/__init__.py +1 -0
  45. jbr_inference-0.1.0/jbr_inference/models/registry.py +279 -0
  46. jbr_inference-0.1.0/jbr_inference/models/registry.toml +83 -0
  47. jbr_inference-0.1.0/jbr_inference/serving/README.md +59 -0
  48. jbr_inference-0.1.0/jbr_inference/serving/__init__.py +1 -0
  49. jbr_inference-0.1.0/jbr_inference/serving/admin.py +389 -0
  50. jbr_inference-0.1.0/jbr_inference/serving/app.py +254 -0
  51. jbr_inference-0.1.0/jbr_inference/serving/backends/__init__.py +6 -0
  52. jbr_inference-0.1.0/jbr_inference/serving/backends/base.py +80 -0
  53. jbr_inference-0.1.0/jbr_inference/serving/backends/fake.py +97 -0
  54. jbr_inference-0.1.0/jbr_inference/serving/download.py +283 -0
  55. jbr_inference-0.1.0/jbr_inference/serving/errors.py +61 -0
  56. jbr_inference-0.1.0/jbr_inference/serving/origin_guard.py +35 -0
  57. jbr_inference-0.1.0/jbr_inference/serving/router.py +230 -0
  58. jbr_inference-0.1.0/jbr_inference/serving/schemas.py +139 -0
  59. jbr_inference-0.1.0/pyproject.toml +140 -0
  60. jbr_inference-0.1.0/scripts/npu/spike_probe_static_seqlen128.py +82 -0
  61. jbr_inference-0.1.0/tests/fixtures/registry_with_invalid_entry.toml +21 -0
  62. jbr_inference-0.1.0/tests/test_api.py +124 -0
  63. jbr_inference-0.1.0/tests/test_bench_runner.py +254 -0
  64. jbr_inference-0.1.0/tests/test_download.py +715 -0
  65. jbr_inference-0.1.0/tests/test_gpu_backend.py +353 -0
  66. jbr_inference-0.1.0/tests/test_management.py +904 -0
  67. jbr_inference-0.1.0/tests/test_npu_backend.py +483 -0
  68. jbr_inference-0.1.0/tests/test_registry.py +58 -0
  69. jbr_inference-0.1.0/tests/test_router.py +88 -0
  70. jbr_inference-0.1.0/tests/test_smoke.py +11 -0
  71. jbr_inference-0.1.0/tests/test_streaming.py +245 -0
  72. jbr_inference-0.1.0/tests/test_streaming_gpu.py +129 -0
  73. jbr_inference-0.1.0/uv.lock +2694 -0
@@ -0,0 +1,27 @@
1
+ name: ci
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ test:
13
+ runs-on: ubuntu-latest
14
+ strategy:
15
+ fail-fast: false
16
+ matrix:
17
+ python: ['3.11', '3.12', '3.13']
18
+ steps:
19
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
20
+ with:
21
+ persist-credentials: false
22
+ - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
23
+ with:
24
+ python-version: ${{ matrix.python }}
25
+ - run: python -m pip install 'uv==0.11.30'
26
+ - run: uv sync --locked --python "${{ matrix.python }}"
27
+ - run: uv run pytest -q -m "not gpu and not npu"
@@ -0,0 +1,32 @@
1
+ name: gitleaks
2
+
3
+ on:
4
+ push:
5
+ pull_request:
6
+
7
+ permissions:
8
+ contents: read
9
+
10
+ jobs:
11
+ scan:
12
+ runs-on: ubuntu-latest
13
+ steps:
14
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
15
+ with:
16
+ fetch-depth: 0
17
+ persist-credentials: false
18
+ - name: Install gitleaks (official release, pinned SHA-256)
19
+ env:
20
+ VERSION: '8.30.1'
21
+ SHA256: 551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb
22
+ run: |
23
+ set -euo pipefail
24
+ archive="gitleaks_${VERSION}_linux_x64.tar.gz"
25
+ curl --fail --silent --show-error --location --max-time 120 \
26
+ --output "$RUNNER_TEMP/$archive" \
27
+ "https://github.com/gitleaks/gitleaks/releases/download/v${VERSION}/$archive"
28
+ echo "$SHA256 $RUNNER_TEMP/$archive" | sha256sum --check --strict
29
+ tar -xzf "$RUNNER_TEMP/$archive" -C "$RUNNER_TEMP" gitleaks
30
+ - name: Scan the whole history (blocking)
31
+ run: |
32
+ "$RUNNER_TEMP/gitleaks" git --config .gitleaks.toml --redact --no-banner --exit-code 1 --verbose .
@@ -0,0 +1,205 @@
1
+ name: release
2
+
3
+ # Triggered by a version tag. Three jobs:
4
+ # build : read-only, no environment; builds sdist + wheel and uploads them as a one-day artifact.
5
+ # publish-test : runs in the `release-test` environment (manual approval); publishes to TestPyPI.
6
+ # Mandatory for a package's first release; skip it afterwards by setting the
7
+ # repository variable SKIP_TESTPYPI to 'true'.
8
+ # publish : runs in the `release` environment (manual approval); publishes to PyPI, then creates
9
+ # the GitHub release.
10
+ # Each publishing job refuses to publish unless the SHA-256 of the artifact equals vars.ARCHIVE_SHA256
11
+ # of its own environment.
12
+ on:
13
+ push:
14
+ tags: ['v*']
15
+
16
+ permissions:
17
+ contents: read
18
+
19
+ concurrency:
20
+ group: release-${{ github.ref }}
21
+ cancel-in-progress: false
22
+
23
+ jobs:
24
+ build:
25
+ runs-on: ubuntu-latest
26
+ permissions:
27
+ contents: read
28
+ steps:
29
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
30
+ with:
31
+ persist-credentials: false
32
+ - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
33
+ with:
34
+ python-version: '3.12'
35
+ - name: Check the tag and its changelog section
36
+ env:
37
+ TAG: ${{ github.ref_name }}
38
+ run: |
39
+ set -euo pipefail
40
+ if ! printf '%s' "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$'; then
41
+ echo "::error::tag '$TAG' is not of the form v<major>.<minor>.<patch>[-prerelease]"
42
+ exit 1
43
+ fi
44
+ version="${TAG#v}"
45
+ awk -v v="$version" '
46
+ /^## \[/ { if (found) exit; if (index($0, "## [" v "]") == 1) found = 1; next }
47
+ found { print }
48
+ ' CHANGELOG.md > "$RUNNER_TEMP/notes.md"
49
+ if ! grep -q '[^[:space:]]' "$RUNNER_TEMP/notes.md"; then
50
+ echo "::error::CHANGELOG.md has no non-empty section '## [$version]'"
51
+ exit 1
52
+ fi
53
+ - name: Build sdist and wheel
54
+ env:
55
+ TAG: ${{ github.ref_name }}
56
+ run: |
57
+ set -euo pipefail
58
+ python -m pip install 'build==1.6.1' 'twine==7.0.0'
59
+ SOURCE_DATE_EPOCH="$(git log -1 --format=%ct)" python -m build --outdir dist
60
+ python -m twine check dist/*
61
+ python - "${TAG#v}" <<'PY'
62
+ import glob, sys
63
+ from packaging.utils import parse_sdist_filename, parse_wheel_filename
64
+ from packaging.version import Version
65
+ expected = Version(sys.argv[1])
66
+ found = []
67
+ for path in sorted(glob.glob("dist/*")):
68
+ name = path.split("/")[-1]
69
+ if name.endswith(".whl"):
70
+ found.append((name, parse_wheel_filename(name)[1]))
71
+ elif name.endswith(".tar.gz"):
72
+ found.append((name, parse_sdist_filename(name)[1]))
73
+ if not found:
74
+ sys.exit("no distribution was built")
75
+ for name, version in found:
76
+ if version != expected:
77
+ sys.exit(f"{name}: version {version} differs from the tag ({expected})")
78
+ PY
79
+ - name: Write the canonical SHA256SUMS
80
+ run: |
81
+ set -euo pipefail
82
+ cd dist
83
+ find . -maxdepth 1 -type f ! -name SHA256SUMS -printf '%f\n' | LC_ALL=C sort \
84
+ | xargs -d '\n' sha256sum -- > SHA256SUMS
85
+ cat SHA256SUMS
86
+ - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
87
+ with:
88
+ name: dist
89
+ path: dist/
90
+ retention-days: 1
91
+ if-no-files-found: error
92
+
93
+ publish-test:
94
+ needs: build
95
+ if: ${{ vars.SKIP_TESTPYPI != 'true' }}
96
+ runs-on: ubuntu-latest
97
+ environment: release-test
98
+ permissions:
99
+ contents: read
100
+ id-token: write
101
+ steps:
102
+ - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
103
+ with:
104
+ name: dist
105
+ path: dist
106
+ - name: Verify the artifact against vars.ARCHIVE_SHA256
107
+ env:
108
+ ARCHIVE_SHA256: ${{ vars.ARCHIVE_SHA256 }}
109
+ run: |
110
+ set -euo pipefail
111
+ cd dist
112
+ if [ -n "$(find . -mindepth 1 ! -type f -print -quit)" ] || [ -n "$(find . -mindepth 2 -print -quit)" ]; then
113
+ echo "::error::the artifact must contain regular files at its root only"
114
+ exit 1
115
+ fi
116
+ find . -maxdepth 1 -type f ! -name SHA256SUMS -printf '%f\n' | LC_ALL=C sort \
117
+ | xargs -d '\n' sha256sum -- > "$RUNNER_TEMP/SHA256SUMS.recomputed"
118
+ actual="$(sha256sum "$RUNNER_TEMP/SHA256SUMS.recomputed" | cut -d ' ' -f 1)"
119
+ if [ -z "$ARCHIVE_SHA256" ]; then
120
+ echo "::error::vars.ARCHIVE_SHA256 is not set on this environment; refusing to publish"
121
+ exit 1
122
+ fi
123
+ if [ "$actual" != "$ARCHIVE_SHA256" ]; then
124
+ echo "::error::artifact SHA-256 ($actual) differs from vars.ARCHIVE_SHA256 ($ARCHIVE_SHA256); refusing to publish"
125
+ exit 1
126
+ fi
127
+ - name: Keep only the distributions for upload
128
+ run: |
129
+ set -euo pipefail
130
+ mkdir upload
131
+ mv dist/*.whl dist/*.tar.gz upload/
132
+ - uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3
133
+ with:
134
+ repository-url: https://test.pypi.org/legacy/
135
+ packages-dir: upload/
136
+
137
+ publish:
138
+ needs: [build, publish-test]
139
+ if: ${{ !cancelled() && !failure() }}
140
+ runs-on: ubuntu-latest
141
+ environment: release
142
+ permissions:
143
+ contents: write
144
+ id-token: write
145
+ steps:
146
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
147
+ with:
148
+ persist-credentials: false
149
+ sparse-checkout: CHANGELOG.md
150
+ sparse-checkout-cone-mode: false
151
+ - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
152
+ with:
153
+ name: dist
154
+ path: dist
155
+ - name: Verify the artifact against vars.ARCHIVE_SHA256
156
+ env:
157
+ ARCHIVE_SHA256: ${{ vars.ARCHIVE_SHA256 }}
158
+ run: |
159
+ set -euo pipefail
160
+ cd dist
161
+ if [ -n "$(find . -mindepth 1 ! -type f -print -quit)" ] || [ -n "$(find . -mindepth 2 -print -quit)" ]; then
162
+ echo "::error::the artifact must contain regular files at its root only"
163
+ exit 1
164
+ fi
165
+ find . -maxdepth 1 -type f ! -name SHA256SUMS -printf '%f\n' | LC_ALL=C sort \
166
+ | xargs -d '\n' sha256sum -- > "$RUNNER_TEMP/SHA256SUMS.recomputed"
167
+ actual="$(sha256sum "$RUNNER_TEMP/SHA256SUMS.recomputed" | cut -d ' ' -f 1)"
168
+ if [ -z "$ARCHIVE_SHA256" ]; then
169
+ echo "::error::vars.ARCHIVE_SHA256 is not set on this environment; refusing to publish"
170
+ exit 1
171
+ fi
172
+ if [ "$actual" != "$ARCHIVE_SHA256" ]; then
173
+ echo "::error::artifact SHA-256 ($actual) differs from vars.ARCHIVE_SHA256 ($ARCHIVE_SHA256); refusing to publish"
174
+ exit 1
175
+ fi
176
+ cp "$RUNNER_TEMP/SHA256SUMS.recomputed" SHA256SUMS
177
+ - name: Extract the release notes from CHANGELOG.md
178
+ env:
179
+ TAG: ${{ github.ref_name }}
180
+ run: |
181
+ set -euo pipefail
182
+ version="${TAG#v}"
183
+ awk -v v="$version" '
184
+ /^## \[/ { if (found) exit; if (index($0, "## [" v "]") == 1) found = 1; next }
185
+ found { print }
186
+ ' CHANGELOG.md > "$RUNNER_TEMP/notes.md"
187
+ grep -q '[^[:space:]]' "$RUNNER_TEMP/notes.md"
188
+ - name: Keep only the distributions for upload
189
+ run: |
190
+ set -euo pipefail
191
+ mkdir upload
192
+ cp dist/*.whl dist/*.tar.gz upload/
193
+ - uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3
194
+ with:
195
+ packages-dir: upload/
196
+ - name: Create the GitHub release
197
+ env:
198
+ GH_TOKEN: ${{ github.token }}
199
+ TAG: ${{ github.ref_name }}
200
+ run: |
201
+ set -euo pipefail
202
+ flags=()
203
+ if [[ "$TAG" == *-* ]]; then flags+=(--prerelease); fi
204
+ gh release create "$TAG" dist/* --repo "$GITHUB_REPOSITORY" --verify-tag \
205
+ --title "$TAG" --notes-file "$RUNNER_TEMP/notes.md" "${flags[@]}"
@@ -0,0 +1,28 @@
1
+ # --- Python ---
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ .eggs/
6
+ .pytest_cache/
7
+ .ruff_cache/
8
+ .mypy_cache/
9
+ build/
10
+ dist/
11
+
12
+ # --- venvs (un venv par backend — jamais mélangés, cf. pyproject.toml) ---
13
+ .venv/
14
+ .venv-gpu/
15
+ .venv-npu/
16
+
17
+ # --- Poids de modèles (volumineux, acquis par runbook — jamais committés) ---
18
+ models/weights/
19
+ *.gguf
20
+ *.bin
21
+ *.onnx
22
+ *.xml
23
+
24
+ # --- Artefacts CI / SBOM ---
25
+ bom.*
26
+
27
+ # NB : les résultats de bench committés (docs/bench/results/, docs/bench/proofs/ — JSON/Markdown,
28
+ # petits) ne sont PAS ignorés : ce sont les preuves d'exécution réelle des backends.
@@ -0,0 +1,6 @@
1
+ # gitleaks configuration: the default ruleset, extended, with no allowlist.
2
+ # Add an allowlist entry only for a proven false positive, with a comment that says why.
3
+ title = "gitleaks config"
4
+
5
+ [extend]
6
+ useDefault = true
@@ -0,0 +1,41 @@
1
+ # Allowlist trivy — une CVE non pertinente se déclare ICI, justifiée + datée, jamais en
2
+ # assouplissant le seuil (--severity/--exit-code) de la configuration CI.
3
+
4
+ # CVE-2026-4372, CVE-2026-5241 (transformers==4.57.6, RCE via trust_remote_code) — 2026-07-21.
5
+ # `transformers` est une dépendance WSL-only de l'extra [npu] (jbr_inference/backends/npu/convert_model.py,
6
+ # conversion/quantization du modèle) : jamais installée dans le venv de BASE (celui de la CI,
7
+ # `uv sync` sans --extra) ni dans le runtime réel du service (jbr_inference/backends/npu/server.py sur la
8
+ # machine cible, qui ne dépend que d'openvino + tokenizers, cf.
9
+ # jbr_inference/backends/npu/README.md). Le
10
+ # modèle converti (Jean-Baptiste/camembert-ner, HF public, checkpoint fixe) est chargé une
11
+ # fois en local par un développeur, jamais `trust_remote_code=True`, jamais exposé à une
12
+ # entrée réseau — la surface RCE de ces CVE ne s'applique pas à cet usage.
13
+ # Correctif amont : fixé en transformers>=5.3.0/5.5.0 selon la CVE. Non adoptable ici :
14
+ # `optimum-intel` (dernière version publiée, 2.0.0) déclare une contrainte dure
15
+ # `transformers<5.1` — `uv sync --extra npu` refuse de résoudre `transformers>=5.5` avec
16
+ # `optimum-intel>=1.24` (conflit non satisfiable, vérifié), malgré une conversion
17
+ # fonctionnellement identique testée manuellement avec transformers==5.5.0 (export +
18
+ # quantization + compile + inférence produisent les mêmes prédictions qu'avec 4.57.6). Écart
19
+ # amont réel (optimum-intel pas encore aligné sur transformers 5.x récent), pas un choix de ce
20
+ # repo — cf. pyproject.toml (extra [npu]) pour le détail. À retirer dès qu'une version
21
+ # d'optimum-intel relève ce plafond et permet `transformers>=5.5,<6`.
22
+ CVE-2026-4372
23
+ CVE-2026-5241
24
+
25
+ # CVE-2026-80047 (transformers==4.57.6, écriture de fichier non autorisée via
26
+ # `GenerativePreTrainedModel.load_custom_generate()`) et CVE-2026-9856 (traversée de
27
+ # chemin via `save_pretrained`/nom de template de chat) — 2026-10-27, trouvées par le
28
+ # gate pip-audit/trivy nightly (aucun changement de code associé).
29
+ # Même périmètre et même justification que CVE-2026-4372/5241 ci-dessus : `transformers`
30
+ # est une dépendance WSL-only de l'extra [npu] (conversion/quantization locale), jamais
31
+ # installée dans le venv de BASE de la CI ni dans le runtime réel du service — le modèle
32
+ # converti (checkpoint HF public fixe) est chargé localement par un développeur, jamais
33
+ # via une entrée réseau non fiable, donc l'écriture de fichier arbitraire et la traversée
34
+ # de chemin de ces deux CVE n'ont pas de surface d'exploitation ici.
35
+ # Correctif amont : CVE-2026-9856 fixée en transformers>=5.10.0 ; CVE-2026-80047 n'a
36
+ # aucun correctif publié à ce jour. Non adoptable : même plafond `optimum-intel<2.0`
37
+ # imposant `transformers<5.1` déjà documenté ci-dessus (conflit non satisfiable avec
38
+ # `uv sync --extra npu`). Expire le 2027-01-27 — à réévaluer à cette date (nouvelle
39
+ # version d'optimum-intel levant le plafond, ou correctif publié pour CVE-2026-80047).
40
+ CVE-2026-80047 exp:2027-01-27
41
+ CVE-2026-9856 exp:2027-01-27
@@ -0,0 +1,21 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file.
4
+ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project adheres
5
+ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [0.1.0] - 2026-12-04
8
+
9
+ ### Added
10
+
11
+ - OpenAI-compatible HTTP API (`GET /v1/models`, `POST /v1/chat/completions` with optional SSE streaming,
12
+ `POST /v1/anonymize`) served by an ASGI application.
13
+ - Model-to-backend registry (`jbr_inference/models/registry.toml`) and a router that never couples one
14
+ backend to another.
15
+ - Deterministic in-memory `fake` backend: the API runs with no GPU, no NPU and no model download.
16
+ - GPU backend: adapter and lifecycle manager for a local llama.cpp server (CUDA), optional `gpu` extra.
17
+ - NPU backend: OpenVINO service for a static-shape token-classification encoder, with a conversion script,
18
+ optional `npu` extra.
19
+ - Optional management API (model switch, download, deactivate), mounted only when
20
+ `JBR_INFERENCE_ENABLE_ADMIN=1`, with a fail-closed `Origin` guard.
21
+ - Benchmark harness that drives the common API, with committed execution proofs and one result set.
@@ -0,0 +1,284 @@
1
+ # EXTENDING — ajouter un backend, ajouter un modèle
2
+
3
+ Ce guide part du code réel (pas d'API imaginée) : chaque commande et chaque
4
+ chemin cités ci-dessous sont vérifiés contre `jbr_inference/serving/backends/base.py`,
5
+ `jbr_inference/serving/router.py`, `jbr_inference/models/registry.py` et les adaptateurs `jbr_inference/backends/gpu/`
6
+ et `jbr_inference/backends/npu/` existants. Il complète les READMEs déjà en place
7
+ (`jbr_inference/serving/README.md`, `jbr_inference/backends/gpu/README.md`, `jbr_inference/backends/npu/README.md`,
8
+ `jbr_inference/models/README.md`) sans les dupliquer : ici, le **walkthrough** — dans quel
9
+ ordre faire quoi, avec quel fichier toucher à chaque étape.
10
+
11
+ ## Vue d'ensemble : où vit quoi
12
+
13
+ ```
14
+ jbr_inference/serving/backends/base.py -> le protocole Backend (contrat neutre)
15
+ jbr_inference/serving/backends/fake.py -> l'implémentation de référence (en mémoire, déterministe)
16
+ jbr_inference/serving/router.py -> résout model -> ModelEntry -> Backend, ne connaît QUE le protocole
17
+ jbr_inference/serving/app.py -> create_app() câble les backends concrets (fake/gpu/npu)
18
+ jbr_inference/models/registry.py -> vocabulaire fermé backend/task, valide au chargement
19
+ jbr_inference/models/registry.toml -> la source de vérité du routage modèle -> backend
20
+ jbr_inference/backends/gpu/, jbr_inference/backends/npu/ -> les adaptateurs réels, protocole Backend, zéro import croisé
21
+ ```
22
+
23
+ Règle structurelle à ne jamais casser : **`jbr_inference/serving/` n'importe jamais un
24
+ backend concret**. Il ne connaît que `jbr_inference.serving.backends.base.Backend`
25
+ (`typing.Protocol`). Ajouter un backend ne doit jamais nécessiter de changer
26
+ une ligne de `jbr_inference/serving/router.py`.
27
+
28
+ ---
29
+
30
+ ## Recette 1 — Ajouter un backend
31
+
32
+ ### Étape 1 — partir de `FakeBackend` comme patron
33
+
34
+ `jbr_inference/serving/backends/fake.py::FakeBackend` est l'implémentation de référence du
35
+ protocole : en mémoire, sans réseau, déterministe. C'est le point de départ
36
+ le plus sûr pour un nouveau backend — copiez sa structure, remplacez le corps
37
+ par vos appels réels.
38
+
39
+ Un backend réel (GPU, NPU) suit plutôt le patron **proxy HTTP** de
40
+ `jbr_inference/backends/gpu/adapter.py::LlamaCppGpuBackend` ou
41
+ `jbr_inference/backends/npu/adapter.py::OpenVinoNpuBackend` : la classe ne dépend que de
42
+ `httpx` (déjà une dépendance de base) et parle à un serveur déjà lancé dans
43
+ son propre process/venv. C'est ce choix qui permet à `jbr_inference/serving/app.py` de
44
+ câbler le backend par défaut sans coupler le venv de base à CUDA ou OpenVINO
45
+ (cf. `jbr_inference/backends/gpu/README.md` §« Mode d'intégration retenu »).
46
+
47
+ ### Étape 2 — implémenter le protocole `Backend`
48
+
49
+ Le protocole est défini dans `jbr_inference/serving/backends/base.py`. Il compte **cinq
50
+ méthodes**, dont **quatre obligatoires** et une optionnelle :
51
+
52
+ ```python
53
+ class Backend(Protocol):
54
+ def health(self) -> bool: ...
55
+
56
+ def available_models(self) -> list[str]: ...
57
+
58
+ def generate(
59
+ self, *, model: str, messages: list[dict[str, str]], **params: Any
60
+ ) -> dict[str, Any]: ...
61
+
62
+ def generate_stream(
63
+ self, *, model: str, messages: list[dict[str, str]], **params: Any
64
+ ) -> Iterator[str]: ...
65
+
66
+ def run(self, *, model: str, task: str, payload: dict[str, Any]) -> dict[str, Any]: ...
67
+ ```
68
+
69
+ - **`health() -> bool`** (obligatoire) — vrai si le backend est disponible.
70
+ Ne doit **jamais lever** : `jbr_inference/serving/router.py::Router.list_models()` capture
71
+ toute exception et retombe sur `status="unloaded"` (cf. `router.py` lignes
72
+ 70-77). Le patron proxy HTTP (`LlamaCppGpuBackend.health()`) attrape
73
+ `httpx.HTTPError` et renvoie `False`.
74
+ - **`available_models() -> list[str]`** (obligatoire) — les `model_id` que ce
75
+ backend peut effectivement servir *maintenant* (introspection réelle, pas
76
+ la liste théorique du registre).
77
+ - **`generate(*, model, messages, **params) -> dict`** (obligatoire) — la voie
78
+ bloquante de `chat`. Retourne `{"role": "assistant", "content": str}`.
79
+ Contrat V1, appelé ssi `stream` est absent ou `False` — ne change jamais de
80
+ forme.
81
+ - **`run(*, model, task, payload) -> dict`** (obligatoire) — les tâches
82
+ non-chat (ex. `anonymize`). Payload et retour opaques pour le routeur,
83
+ spécifiques à la tâche.
84
+ - **`generate_stream(*, model, messages, **params) -> Iterator[str]`**
85
+ (**optionnelle**) — la voie streaming SSE de `chat`, yield des chunks de
86
+ texte bruts. Un backend qui ne la supporte pas la laisse lever
87
+ `NotImplementedError` (comportement Python par défaut d'une méthode de
88
+ `Protocol` non implémentée, ou une implémentation explicite qui la lève) —
89
+ `jbr_inference/serving/router.py` capture ce cas et le traduit en `BackendUnavailableError`
90
+ (503), jamais une perte silencieuse (cf. `router.py`
91
+ `chat_stream_from_resolved()`, bloc `except NotImplementedError`).
92
+
93
+ Toute panne réseau/backend en cours d'appel doit être traduite en
94
+ `jbr_inference.serving.backends.base.BackendUnavailableError` — c'est la seule exception
95
+ que le routeur sait mapper vers un `503 backend_unavailable` propre (jamais
96
+ un 500 nu). Voir `LlamaCppGpuBackend.generate()` pour le patron : `try/except
97
+ httpx.HTTPError` → lève `BackendUnavailableError`.
98
+
99
+ ### Étape 3 — câbler le backend dans `jbr_inference/serving/app.py`
100
+
101
+ `jbr_inference/serving/app.py::create_app()` construit le dict `backends` par défaut :
102
+
103
+ ```python
104
+ resolved_backends: dict[str, Backend] = (
105
+ backends
106
+ if backends is not None
107
+ else {"fake": FakeBackend(), "gpu": LlamaCppGpuBackend(), "npu": OpenVinoNpuBackend()}
108
+ )
109
+ ```
110
+
111
+ Ajoutez votre backend à ce dict, sous la clé qui sera aussi la valeur
112
+ `backend` de ses entrées de registre (étape 4). L'import de votre module doit
113
+ rester **inoffensif dans le venv de base** : si votre backend a des
114
+ dépendances lourdes (comme `optimum-intel`/`torch` pour NPU ou
115
+ `llama-cpp-python` pour GPU), gardez ces imports **locaux aux fonctions qui en
116
+ ont besoin**, jamais au niveau module de l'adaptateur câblé par défaut — sinon
117
+ `uv sync` (venv de base) et la CI cassent à l'import.
118
+
119
+ ### Étape 4 — déclarer le backend dans le registre (vocabulaire fermé)
120
+
121
+ Le champ `backend` d'une entrée `jbr_inference/models/registry.toml` est un **vocabulaire
122
+ fermé**, validé au chargement par `jbr_inference/models/registry.py` :
123
+
124
+ ```python
125
+ VALID_BACKENDS = frozenset({"gpu", "npu", "fake"})
126
+ ```
127
+
128
+ C'est une constante Python, pas une valeur de config — ajouter un nouveau
129
+ backend nécessite d'**éditer cette ligne** dans `jbr_inference/models/registry.py` (et, si
130
+ la tâche servie est nouvelle, la même chose pour `VALID_TASKS`).
131
+
132
+ Comportement réel du registre si vous oubliez cette étape (ou en cas de
133
+ typo) : `_parse_entry()` (`jbr_inference/models/registry.py`) écarte silencieusement
134
+ l'entrée du registre chargé — l'entrée n'apparaît jamais dans
135
+ `ModelRegistry.list()`/`.get()` — et émet un `WARNING` explicite sur le
136
+ logger `jbr_inference.models.registry`, avec le `model_id` concerné et la source du
137
+ fichier :
138
+
139
+ ```
140
+ jbr_inference.models.registry: entrée écartée (backend 'mon-backend' hors vocab fermé
141
+ ['fake', 'gpu', 'npu']) : model_id='...' (source=...)
142
+ ```
143
+
144
+ C'est un **WARN + écarte, jamais un cast silencieux** — le principe
145
+ appliqué uniformément dans ce dépôt. Le comportement est testé par
146
+ `tests/test_registry.py::test_invalid_backend_entry_is_warned_and_discarded`
147
+ (et son pendant `task`, `test_invalid_task_entry_is_warned_and_discarded`),
148
+ sur la fixture `tests/fixtures/registry_with_invalid_entry.toml` — un modèle
149
+ avec `backend = "quantum"` (hors table) qui disparaît du registre chargé,
150
+ tout en laissant les entrées valides intactes
151
+ (`test_valid_entry_survives_alongside_invalid_ones`).
152
+
153
+ Une fois `VALID_BACKENDS` mis à jour, ajoutez une entrée `[[models]]` dans
154
+ `jbr_inference/models/registry.toml` avec `backend = "mon-backend"` et le `task` visé —
155
+ elle devient immédiatement routable.
156
+
157
+ ### Étape 5 — zéro couplage croisé, et comment il est vérifié
158
+
159
+ Un adaptateur backend ne doit **jamais** importer un autre backend. C'est
160
+ vérifié *statiquement* (parsing AST, pas juste une convention) par
161
+ `tests/test_gpu_backend.py::test_backends_gpu_never_imports_npu` : le test
162
+ parcourt l'AST de chaque fichier `.py` sous `jbr_inference/backends/gpu/` et échoue si un
163
+ `import`/`from ... import ...` référence un module dont un segment de nom est
164
+ `npu`. Si vous ajoutez un backend, envisagez un test analogue pour votre
165
+ propre répertoire.
166
+
167
+ ### Étape 6 — tests à écrire
168
+
169
+ En reprenant le patron de `tests/test_gpu_backend.py`/`tests/test_npu_backend.py` :
170
+
171
+ - Le protocole en isolation (`health`, `available_models`, `generate`,
172
+ `run`, et `generate_stream` si supporté) avec un transport `httpx` mocké
173
+ (`httpx.MockTransport`, comme `LlamaCppGpuBackend` et `OpenVinoNpuBackend`
174
+ le font déjà) — jamais un vrai process réseau en test hors-ligne/CI.
175
+ - Le routage bout-en-bout via `ModelRegistry` + `Router` (comme
176
+ `test_registry_routes_gpu_model_to_gpu_backend_without_router_changes`) :
177
+ prouve que le routeur n'a pas eu besoin d'être modifié.
178
+ - Le cas `backend_unavailable` (503) quand le serveur réel n'est pas lancé.
179
+ - Si le backend a un mode réel nécessitant du matériel/un serveur externe,
180
+ ajoutez un marker pytest dédié dans `pyproject.toml`
181
+ (`[tool.pytest.ini_options].markers`, cf. `gpu`/`npu` existants) et
182
+ désélectionnez-le en CI (`-m "not gpu and not npu and not <votre-marker>"`).
183
+
184
+ ---
185
+
186
+ ## Recette 2 — Ajouter un modèle
187
+
188
+ ### GPU (llama.cpp-server)
189
+
190
+ 1. **Acquérir les poids** (GGUF), jamais committés (`.gitignore` :
191
+ `models/weights/`, `*.gguf`). Suivre le patron de
192
+ `jbr_inference/backends/gpu/README.md` §2 (téléchargement direct, licence vérifiée
193
+ ungated, `sha256sum` de contrôle documenté dans le README ou un
194
+ `docs/bench/proofs/*.md`).
195
+ 2. **Déclarer l'entrée** dans `jbr_inference/models/registry.toml` :
196
+ ```toml
197
+ [[models]]
198
+ model_id = "mon-modele-gguf"
199
+ backend = "gpu"
200
+ task = "chat"
201
+ quant_policy = "GGUF Q4_K_M (...)"
202
+
203
+ [models.endpoint]
204
+ model_path = "models/weights/mon-modele.gguf"
205
+ base_url = "http://127.0.0.1:8081"
206
+ note = "..."
207
+ ```
208
+ `model_path` est le chemin résolu par `GpuLifecycleManager` pour l'endpoint
209
+ admin `activate` (surface `/admin/*`, opt-in) — absent, l'entrée reste
210
+ routable mais non switchable via cet endpoint (404
211
+ `model_path_missing`).
212
+ 3. **Contraintes réelles** : le serveur `llama.cpp-server` est piloté par
213
+ `GpuBackendConfig` (`jbr_inference/backends/gpu/config.py`, préfixe d'env `JBR_GPU_*`) —
214
+ `model_id`/`model_path`/`host`/`port`/`n_gpu_layers`/`n_ctx` s'y règlent,
215
+ jamais en dur dans le code. La VRAM disponible borne la taille du modèle
216
+ et le contexte (`n_ctx`) — cf. `jbr_inference/models/README.md` §« Politiques de
217
+ quantization » pour le compromis Q4_K_M retenu sur une RTX 3060 12 Go.
218
+ 4. **Tester** :
219
+ ```bash
220
+ UV_PROJECT_ENVIRONMENT=.venv-gpu uv sync --extra gpu --python 3.12
221
+ uv run pytest -q -m "not gpu and not npu" # hors-ligne, mocks httpx — CI
222
+ uv run pytest -m gpu # local uniquement, serveur réel requis
223
+ ```
224
+
225
+ ### NPU (OpenVINO)
226
+
227
+ 1. **Convertir + quantifier** le modèle HF vers OpenVINO IR via
228
+ `jbr_inference/backends/npu/convert_model.py` (venv dédié `.venv-npu`, jamais au
229
+ runtime du service) :
230
+ ```bash
231
+ UV_PROJECT_ENVIRONMENT=.venv-npu uv sync --extra npu --python 3.12
232
+ .venv-npu/bin/python -m jbr_inference.backends.npu.convert_model \
233
+ --model-id <org/modele-hf> --out models/weights/<nom>
234
+ ```
235
+ 2. **Contrainte réelle : shape statique obligatoire.** Le device NPU ne
236
+ compile pas de shape dynamique — `convert_model.py` fige
237
+ `seq_len` à l'export via `model.model.reshape({"input_ids": [1, seq_len],
238
+ "attention_mask": [1, seq_len]})` (défaut `DEFAULT_SEQ_LEN = 128`,
239
+ `--seq-len` pour changer). Toute entrée est paddée/tronquée à cette
240
+ longueur *avant* l'inférence (`jbr_inference/backends/npu/inference.py`, fonctions
241
+ `pad_or_truncate`/`build_attention_mask`) — jamais laissée à taille
242
+ variable. Ce n'est pas une limitation à contourner : c'est la condition de
243
+ compilation sur `NPU` (cf. `docs/npu/SPIKE.md`, verdict GO NPU).
244
+ 3. **Quantization retenue : INT8 poids uniquement**
245
+ (`OVWeightQuantizationConfig(bits=8, sym=True)`), pas la quantization
246
+ poids+activations — cette dernière a cassé le `compile_model()` en shape
247
+ statique sur OpenVINO 2026.2.1 (`jbr_inference/backends/npu/README.md` §1, détail du
248
+ bug reproductible). Si vous ajoutez un modèle, partez de ce même
249
+ régime tant que le bug amont n'est pas corrigé.
250
+ 4. **Déclarer l'entrée** dans `jbr_inference/models/registry.toml` avec `backend = "npu"`,
251
+ `task = "anonymize"` (ou une nouvelle `task` si le modèle sert autre chose
252
+ — auquel cas, ajoutez-la d'abord à `VALID_TASKS` dans `jbr_inference/models/registry.py`,
253
+ même mécanique WARN+écarte que pour `backend`, cf. Recette 1 étape 4).
254
+ 5. **Contrainte device** : `NpuBackendConfig.device` (préfixe d'env
255
+ `JBR_NPU_*`) est aussi un vocabulaire fermé `{"NPU", "CPU"}`
256
+ (`jbr_inference/backends/npu/config.py::VALID_DEVICES`) — toute autre valeur est WARN +
257
+ repli sur `"NPU"` (le défaut), jamais propagée telle quelle à
258
+ `openvino.Core().compile_model()`.
259
+ 6. **Tester** — patron des tests purs (pas de service requis) dans
260
+ `tests/test_npu_backend.py` : `pad_or_truncate`, `build_attention_mask`,
261
+ `extract_entities` (fusion d'entités adjacentes de même label — limite
262
+ connue du schéma IO du NER, pas un bug), puis :
263
+ ```bash
264
+ uv run pytest -q -m "not gpu and not npu" # hors-ligne (encodeur factice, MockTransport) — CI
265
+ GATEWAY_IP=$(ip route show default | awk '{print $3}')
266
+ JBR_NPU_BASE_URL="http://$GATEWAY_IP:8090" uv run pytest -m npu # local uniquement, service réel requis
267
+ ```
268
+
269
+ ---
270
+
271
+ ## Checklist avant merge
272
+
273
+ - [ ] Le nouveau backend implémente les 4 méthodes obligatoires du protocole
274
+ (+ `generate_stream` si le streaming est pertinent).
275
+ - [ ] `jbr_inference/serving/router.py` n'a pas été modifié pour ajouter le backend (si
276
+ c'est le cas, quelque chose a fuité hors du protocole).
277
+ - [ ] `VALID_BACKENDS`/`VALID_TASKS` (`jbr_inference/models/registry.py`) mis à jour si
278
+ nécessaire, avec le test `WARN + écarte` correspondant.
279
+ - [ ] Aucun import croisé vers un autre backend (vérifié par un test AST,
280
+ cf. `test_backends_gpu_never_imports_npu`).
281
+ - [ ] Tests hors-ligne (mocks) passent en CI ; tests marqués
282
+ `gpu`/`npu`/`<nouveau-marker>` désélectionnés par défaut.
283
+ - [ ] Import du module câblé par défaut dans `jbr_inference/serving/app.py` reste possible
284
+ depuis le venv de base (pas de dépendance lourde au niveau module).