docs(deploy): refresh for the post-launch deployment iteration
Browse filesCaptures the architecture and operational decisions made during the
local Docker bring-up: the unified RESEARCH_ROOT / CHECKPOINTS_ROOT
layout, the single preloaded gunicorn worker, the AppConfig skip-list
for management commands, the share_memory and TransE-init dim-
expansion monkey-patches around experiment.prepare(), the MultiProx
symmetry safeguard, the bundled Loader caches that keep cold-start
RAM under control, and the WSL2 / shm_size requirements for running
the container locally.
Also corrects every HF Hub reference to the case-sensitive Bani57
namespace (account is registered as "Bani57", not "bani57"), and
clarifies the HF_TOKEN env var as recommended (read-scope token
lifts anonymous rate limits and roughly triples cold-start download
throughput; required only for private repos).
Files changed (11)
- .claude/plans/deploy_huggingface_spaces.md+16-16
- CLAUDE.md+3-3
- README.md+1-1
- docs/README.md+1-1
- docs/explanation/architecture.md+18-14
- docs/explanation/inference-lifecycle.md+33-5
- docs/glossary.md+2-2
- docs/guides/deploy.md+7-7
- docs/guides/local-development.md+10-2
- docs/reference/backend-services.md+10-1
- src/backend/README.md+10-9
11 unmodified lines12131415161718192 unmodified lines222324252627289 unmodified lines383940414243445 unmodified lines505152535455565758596070 unmodified lines13113213313413513613745 unmodified lines1831841851861871881891901911921931941951961971981992002012022032042052062071 unmodified line2092102112122132142152162172185 unmodified lines2242252262272282292302312322331 unmodified line23523623723823924024111 unmodified lines- Free, no credit card. 16 GB RAM, 2 vCPU, 50 GB ephemeral disk, 7860 default port.- Native Docker β we provide a `Dockerfile`, HF builds and runs it.- Purpose-built for ML demos (the very thing this site is).- Checkpoints move from Google Drive to a free HF Hub model repo (`bani57/checkpoints`), served by HF's CDN β much faster than `gdown`, no quota games, resumable uploads/downloads.- Space is `bani57/website` β public URL `https://bani57-website.hf.space`. (HF Spaces URLs are always `<owner>-<spacename>.hf.space`; a bare `bani57.hf.space` isn't possible.)- A single container serves both the API (Django/Gunicorn) and the built Vue SPA (via WhiteNoise) on the same origin β no CORS, one URL.Trade-off accepted: free Spaces sleep after 48 h idle (first hit wakes it, ~2 min cold start because checkpoints are re-pulled from HF Hub on a fresh ephemeral disk). \$5/mo Persistent Storage upgrade eliminates this if it ever bothers us.2 unmodified lines```βββββββββββββββββββββββββββββββββββββββ HF Space: bani57/website βBrowser βHTTPSββΆβ https://bani57-website.hf.space ββ (Docker container, port 7860) ββ β9 unmodified linesβ β² snapshot_download() at boot ββββββΌββββββββββββββββββββββββββββββββββHF Hub model repo: bani57/checkpoints(free, unlimited, CDN-backed, resumable)```5 unmodified lines- `docker-compose.yml` (repo root) β local dev convenience only; HF Spaces ignores it and consumes only the Dockerfile.- `.dockerignore` β keep `node_modules`, `.git`, `src/research/**/checkpoints`, `data.zip`, `docs/`, screenshots, `*.npz`, `*.gz` out of the build context.- `entrypoint.sh` β runs `huggingface_hub.snapshot_download` (idempotent), then `exec gunicorn β¦` on `0.0.0.0:7860`.- `scripts/upload_checkpoints.py` (NEW) β one-shot script that walks the local research checkpoint dirs and pushes everything to `bani57/checkpoints` on HF Hub, preserving directory structure and resumable on partial failure.- Top-level `README.md` for the Space (a thin file with YAML front-matter HF requires; rendered as the Space card). Either commit it at repo root and let the Space repo serve as the deploy target, or maintain a small Space-only fork β see Deployment Steps for the chosen flow.**Modified:**- `src/backend/api/services/registry.py` β replace the `gdown` Google-Drive call with `huggingface_hub.snapshot_download(repo_id="bani57/checkpoints", local_dir=β¦)`. Keep the registry's lazy-load pattern intact. Mirror directory layout exactly so existing scan logic still finds files.- `src/backend/api/apps.py` β *remove* the eager checkpoint download from `AppConfig.ready()`. Downloads happen in `entrypoint.sh` *before* gunicorn starts, so workers never block.- `src/backend/research_api/settings.py` β add WhiteNoise to `MIDDLEWARE` (right after `SecurityMiddleware`); set `STATIC_ROOT = BASE_DIR / "staticfiles"`, `STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"`; environment-drive `ALLOWED_HOSTS` and `CORS_ALLOWED_ORIGINS` (replace hardcoded `bani57.pythonanywhere.com` with `bani57-website.hf.space`); read `CHECKPOINTS_DIR` from env (default `/tmp/checkpoints` in container, repo path in dev).- `src/backend/research_api/urls.py` β add SPA shell view: `re_path(r"^(?!api/|static/).*$", spa_index_view)` returning `dist/index.html` for any non-API, non-static path. **This does not replace the Lara Croft 404** β Vue Router's existing `/:pathMatch(.*)*` route still catches unknown paths and renders `NotFoundView.vue` (Lara) client-side. Django's job ends at handing the SPA shell to the browser.70 unmodified lines#!/bin/shset -epython -c "from huggingface_hub import snapshot_download; \snapshot_download(repo_id='bani57/checkpoints', \local_dir='/tmp/checkpoints', \local_dir_use_symlinks=False, \max_workers=4)"45 unmodified lines**3. Create the repo (one-time, public).**```bashhuggingface-cli repo create checkpoints --type model --yes# Repo URL: https://huggingface.co/bani57/checkpoints```**4. Upload, preserving directory layout.** The remote layout matches the on-disk one exactly so the Django registry's existing scan logic finds files unchanged.```bash# COINs graph completion (~2.4 GB)huggingface-cli upload bani57/checkpoints \src/research/COINs-KGGeneration/graph_completion/checkpoints \COINs-KGGeneration/graph_completion/checkpoints \--repo-type model# COINs graph generation / DIGRESS (~2.6 GB)huggingface-cli upload bani57/checkpoints \src/research/COINs-KGGeneration/graph_generation/checkpoints \COINs-KGGeneration/graph_generation/checkpoints \--repo-type model# MultiProxAn (~364 MB)huggingface-cli upload bani57/checkpoints \src/research/MultiProxAn/checkpoints \MultiProxAn/checkpoints \--repo-type model1 unmodified line`huggingface-cli upload` chunks files and is resumable on retry. Total upload at typical home upstream (~10 MB/s) β 15β20 min.**5. Verify.** Open <https://huggingface.co/bani57/checkpoints/tree/main>, confirm the three top-level folders. Then locally:```bashpython -c "from huggingface_hub import snapshot_download; \snapshot_download(repo_id='bani57/checkpoints', local_dir='/tmp/ck-test')"ls -lah /tmp/ck-test```Expect ~5.4 GB total. This is the same call the container makes at boot.5 unmodified lines1. **Upload checkpoints to HF Hub** β as above.2. **Land the code changes** above on `master` (one PR is fine β single deployment unit).3. **Local smoke test**: `docker compose up --build`, hit `http://localhost:7860`, exercise each demo (KG completion, KG anomaly, MultiProxAn graph generation), verify SSE streaming and the Postman collection in `docs/postman/`. Confirm the Lara Croft page renders at `http://localhost:7860/this/is/a/wrong/path`.4. **Create the Space**: on huggingface.co/new-space, name `bani57/website`, SDK = Docker, hardware = CPU basic (free), visibility = public.5. **Push to the Space**:```bashgit remote add hf https://huggingface.co/spaces/bani57/websitegit push hf master:main```HF Spaces uses git on a `main` branch. First build takes ~20β30 min (mamba env solve + GPU torch + apt deps + frontend build + first checkpoint download).1 unmodified line- `DJANGO_SECRET_KEY` β generate fresh (`python -c "import secrets; print(secrets.token_urlsafe(50))"`).- `DJANGO_DEBUG=False`.- `DJANGO_ALLOWED_HOSTS=bani57-website.hf.space`.- `HF_TOKEN` β only if `bani57/checkpoints` is private; for a public model repo no token is needed at runtime.7. **Verification on the live Space**:- Open `https://bani57-website.hf.space` β landing page renders, navigation works, hard-refresh on a deep route still resolves.- Visit `https://bani57-website.hf.space/foo/bar/quux` β Lara 404 page appears (confirms catch-all + Vue Router still cooperate in prod).11 unmodified lines12131415161718192 unmodified lines222324252627289 unmodified lines383940414243445 unmodified lines505152535455565758596070 unmodified lines13113213313413513613745 unmodified lines1831841851861871881891901911921931941951961971981992002012022032042052062071 unmodified line2092102112122132142152162172185 unmodified lines2242252262272282292302312322331 unmodified line23523623723823924024111 unmodified lines- Free, no credit card. 16 GB RAM, 2 vCPU, 50 GB ephemeral disk, 7860 default port.- Native Docker β we provide a `Dockerfile`, HF builds and runs it.- Purpose-built for ML demos (the very thing this site is).- Checkpoints move from Google Drive to a free HF Hub model repo (`Bani57/checkpoints`), served by HF's CDN β much faster than `gdown`, no quota games, resumable uploads/downloads.- Space is `Bani57/website` β public URL `https://bani57-website.hf.space`. (HF Spaces URLs are always `<owner>-<spacename>.hf.space`; a bare `bani57.hf.space` isn't possible.)- A single container serves both the API (Django/Gunicorn) and the built Vue SPA (via WhiteNoise) on the same origin β no CORS, one URL.Trade-off accepted: free Spaces sleep after 48 h idle (first hit wakes it, ~2 min cold start because checkpoints are re-pulled from HF Hub on a fresh ephemeral disk). \$5/mo Persistent Storage upgrade eliminates this if it ever bothers us.2 unmodified lines```βββββββββββββββββββββββββββββββββββββββ HF Space: Bani57/website βBrowser βHTTPSββΆβ https://bani57-website.hf.space ββ (Docker container, port 7860) ββ β9 unmodified linesβ β² snapshot_download() at boot ββββββΌββββββββββββββββββββββββββββββββββHF Hub model repo: Bani57/checkpoints(free, unlimited, CDN-backed, resumable)```5 unmodified lines- `docker-compose.yml` (repo root) β local dev convenience only; HF Spaces ignores it and consumes only the Dockerfile.- `.dockerignore` β keep `node_modules`, `.git`, `src/research/**/checkpoints`, `data.zip`, `docs/`, screenshots, `*.npz`, `*.gz` out of the build context.- `entrypoint.sh` β runs `huggingface_hub.snapshot_download` (idempotent), then `exec gunicorn β¦` on `0.0.0.0:7860`.- `scripts/upload_checkpoints.py` (NEW) β one-shot script that walks the local research checkpoint dirs and pushes everything to `Bani57/checkpoints` on HF Hub, preserving directory structure and resumable on partial failure.- Top-level `README.md` for the Space (a thin file with YAML front-matter HF requires; rendered as the Space card). Either commit it at repo root and let the Space repo serve as the deploy target, or maintain a small Space-only fork β see Deployment Steps for the chosen flow.**Modified:**- `src/backend/api/services/registry.py` β replace the `gdown` Google-Drive call with `huggingface_hub.snapshot_download(repo_id="Bani57/checkpoints", local_dir=β¦)`. Keep the registry's lazy-load pattern intact. Mirror directory layout exactly so existing scan logic still finds files.- `src/backend/api/apps.py` β *remove* the eager checkpoint download from `AppConfig.ready()`. Downloads happen in `entrypoint.sh` *before* gunicorn starts, so workers never block.- `src/backend/research_api/settings.py` β add WhiteNoise to `MIDDLEWARE` (right after `SecurityMiddleware`); set `STATIC_ROOT = BASE_DIR / "staticfiles"`, `STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"`; environment-drive `ALLOWED_HOSTS` and `CORS_ALLOWED_ORIGINS` (replace hardcoded `bani57.pythonanywhere.com` with `bani57-website.hf.space`); read `CHECKPOINTS_DIR` from env (default `/tmp/checkpoints` in container, repo path in dev).- `src/backend/research_api/urls.py` β add SPA shell view: `re_path(r"^(?!api/|static/).*$", spa_index_view)` returning `dist/index.html` for any non-API, non-static path. **This does not replace the Lara Croft 404** β Vue Router's existing `/:pathMatch(.*)*` route still catches unknown paths and renders `NotFoundView.vue` (Lara) client-side. Django's job ends at handing the SPA shell to the browser.70 unmodified lines#!/bin/shset -epython -c "from huggingface_hub import snapshot_download; \snapshot_download(repo_id='Bani57/checkpoints', \local_dir='/tmp/checkpoints', \local_dir_use_symlinks=False, \max_workers=4)"45 unmodified lines**3. Create the repo (one-time, public).**```bashhuggingface-cli repo create checkpoints --type model --yes# Repo URL: https://huggingface.co/Bani57/checkpoints```**4. Upload, preserving directory layout.** The remote layout matches the on-disk one exactly so the Django registry's existing scan logic finds files unchanged.```bash# COINs graph completion (~2.4 GB)huggingface-cli upload Bani57/checkpoints \src/research/COINs-KGGeneration/graph_completion/checkpoints \COINs-KGGeneration/graph_completion/checkpoints \--repo-type model# COINs graph generation / DIGRESS (~2.6 GB)huggingface-cli upload Bani57/checkpoints \src/research/COINs-KGGeneration/graph_generation/checkpoints \COINs-KGGeneration/graph_generation/checkpoints \--repo-type model# MultiProxAn (~364 MB)huggingface-cli upload Bani57/checkpoints \src/research/MultiProxAn/checkpoints \MultiProxAn/checkpoints \--repo-type model1 unmodified line`huggingface-cli upload` chunks files and is resumable on retry. Total upload at typical home upstream (~10 MB/s) β 15β20 min.**5. Verify.** Open <https://huggingface.co/Bani57/checkpoints/tree/main>, confirm the three top-level folders. Then locally:```bashpython -c "from huggingface_hub import snapshot_download; \snapshot_download(repo_id='Bani57/checkpoints', local_dir='/tmp/ck-test')"ls -lah /tmp/ck-test```Expect ~5.4 GB total. This is the same call the container makes at boot.5 unmodified lines1. **Upload checkpoints to HF Hub** β as above.2. **Land the code changes** above on `master` (one PR is fine β single deployment unit).3. **Local smoke test**: `docker compose up --build`, hit `http://localhost:7860`, exercise each demo (KG completion, KG anomaly, MultiProxAn graph generation), verify SSE streaming and the Postman collection in `docs/postman/`. Confirm the Lara Croft page renders at `http://localhost:7860/this/is/a/wrong/path`.4. **Create the Space**: on huggingface.co/new-space, name `Bani57/website`, SDK = Docker, hardware = CPU basic (free), visibility = public.5. **Push to the Space**:```bashgit remote add hf https://huggingface.co/spaces/Bani57/websitegit push hf master:main```HF Spaces uses git on a `main` branch. First build takes ~20β30 min (mamba env solve + GPU torch + apt deps + frontend build + first checkpoint download).1 unmodified line- `DJANGO_SECRET_KEY` β generate fresh (`python -c "import secrets; print(secrets.token_urlsafe(50))"`).- `DJANGO_DEBUG=False`.- `DJANGO_ALLOWED_HOSTS=bani57-website.hf.space`.- `HF_TOKEN` β only if `Bani57/checkpoints` is private; for a public model repo no token is needed at runtime.7. **Verification on the live Space**:- Open `https://bani57-website.hf.space` β landing page renders, navigation works, hard-refresh on a deep route still resolves.- Visit `https://bani57-website.hf.space/foo/bar/quux` β Lara 404 page appears (confirms catch-all + Vue Router still cooperate in prod).
20 unmodified lines212223242526273 unmodified lines31323334353637383940414220 unmodified lines## Architecture- `https://bani57-website.hf.space`: Live website URL (HF Space `bani57/website`, Docker SDK)- `docs/cvAndrejJanchevski.pdf`: My CV, perfectly mapped to a subpage `/cv`, titled "CV".- `docs/janchevski_scalable_2025.pdf`: My PhD thesis, not served on website (only thelink https://infoscience.epfl.ch/entities/publication/87acf391-feef-43a0-b665-7f2f0bc70b2c given), but used as3 unmodified lines- `src/research/COINs-KGGeneration`: repo dump for the COINs KG reasoning and KG generation experiments (3.1 and 4.4 ofPhD thesis)- `src/research/MultiProxAn`: repo dump for the MultiProxAn graph generation experiments (4.3 of PhD thesis)- `https://huggingface.co/bani57/checkpoints`: HF Hub model repo holding all PyTorch checkpoints. The container'sentrypoint pre-warms a `snapshot_download` into `/app/checkpoints` (mirrors the on-disk `src/research/...`layout) before gunicorn starts, and `ModelRegistry._download_checkpoints` is idempotent on warm starts.- `Dockerfile`, `environment.yml`, `entrypoint.sh`, `docker-compose.yml`, `.dockerignore`: deployment assets atthe repo root. `docker compose up --build` reproduces the production container locally on `:7860`.- `scripts/upload_checkpoints.py`: one-shot helper to (re-)publish local checkpoints to `bani57/checkpoints`.- `src/backend`: Django backend and endpoint files location- `src/frontend`: Vue.js and Semantic UI frontend files location20 unmodified lines212223242526273 unmodified lines31323334353637383940414220 unmodified lines## Architecture- `https://bani57-website.hf.space`: Live website URL (HF Space `Bani57/website`, Docker SDK)- `docs/cvAndrejJanchevski.pdf`: My CV, perfectly mapped to a subpage `/cv`, titled "CV".- `docs/janchevski_scalable_2025.pdf`: My PhD thesis, not served on website (only thelink https://infoscience.epfl.ch/entities/publication/87acf391-feef-43a0-b665-7f2f0bc70b2c given), but used as3 unmodified lines- `src/research/COINs-KGGeneration`: repo dump for the COINs KG reasoning and KG generation experiments (3.1 and 4.4 ofPhD thesis)- `src/research/MultiProxAn`: repo dump for the MultiProxAn graph generation experiments (4.3 of PhD thesis)- `https://huggingface.co/Bani57/checkpoints`: HF Hub model repo holding all PyTorch checkpoints. The container'sentrypoint pre-warms a `snapshot_download` into `/app/checkpoints` (mirrors the on-disk `src/research/...`layout) before gunicorn starts, and `ModelRegistry._download_checkpoints` is idempotent on warm starts.- `Dockerfile`, `environment.yml`, `entrypoint.sh`, `docker-compose.yml`, `.dockerignore`: deployment assets atthe repo root. `docker compose up --build` reproduces the production container locally on `:7860`.- `scripts/upload_checkpoints.py`: one-shot helper to (re-)publish local checkpoints to `Bani57/checkpoints`.- `src/backend`: Django backend and endpoint files location- `src/frontend`: Vue.js and Semantic UI frontend files location
12 unmodified lines1314151617181912 unmodified linesLive demos for the PhD thesis _Scalable Methods for Knowledge Graph Reasoning and Generation_ (Andrej Janchevski, EPFL, 2025). The thesis is mirrored at [infoscience.epfl.ch](https://infoscience.epfl.ch/entities/publication/87acf391-feef-43a0-b665-7f2f0bc70b2c); a CV is rendered at `/cv` from `docs/cvAndrejJanchevski.pdf`.The site is a single Django + Vue Docker container. The Django backend serves a stateless REST API at `/api/v1/*` and WhiteNoise serves the built Vue SPA on every other path β same origin, no CORS in production. Deployment target: Hugging Face [Space](docs/glossary.md#hf-space) `bani57/website` β <https://bani57-website.hf.space>.## What's in the demos12 unmodified lines1314151617181912 unmodified linesLive demos for the PhD thesis _Scalable Methods for Knowledge Graph Reasoning and Generation_ (Andrej Janchevski, EPFL, 2025). The thesis is mirrored at [infoscience.epfl.ch](https://infoscience.epfl.ch/entities/publication/87acf391-feef-43a0-b665-7f2f0bc70b2c); a CV is rendered at `/cv` from `docs/cvAndrejJanchevski.pdf`.The site is a single Django + Vue Docker container. The Django backend serves a stateless REST API at `/api/v1/*` and WhiteNoise serves the built Vue SPA on every other path β same origin, no CORS in production. Deployment target: Hugging Face [Space](docs/glossary.md#hf-space) `Bani57/website` β <https://bani57-website.hf.space>.## What's in the demos
123456# DocumentationTechnical documentation for the PhD-research demo website. The site is a single Django + Vue Docker container deployed to a Hugging Face [Space](glossary.md#hf-space) (`bani57/website` β <https://bani57-website.hf.space>) and showcases three research methods from the thesis _Scalable Methods for Knowledge Graph Reasoning and Generation_ (Andrej Janchevski, EPFL, 2025): [COINs](glossary.md#coins), [MultiProxAn](glossary.md#multiproxan) and [KG anomaly correction](glossary.md#task-kg-anomaly).This document is a routing layer. Pick the document type that matches your goal β definitions, understanding, lookup, or task.123456# DocumentationTechnical documentation for the PhD-research demo website. The site is a single Django + Vue Docker container deployed to a Hugging Face [Space](glossary.md#hf-space) (`Bani57/website` β <https://bani57-website.hf.space>) and showcases three research methods from the thesis _Scalable Methods for Knowledge Graph Reasoning and Generation_ (Andrej Janchevski, EPFL, 2025): [COINs](glossary.md#coins), [MultiProxAn](glossary.md#multiproxan) and [KG anomaly correction](glossary.md#task-kg-anomaly).This document is a routing layer. Pick the document type that matches your goal β definitions, understanding, lookup, or task.
8 unmodified lines910111213141516171819202122232 unmodified lines26272829303132333418 unmodified lines535455565758595 unmodified lines65666768697071727310 unmodified lines84858687888990914 unmodified lines969798991001011028 unmodified linesflowchart LRBrowser([Browser])subgraph Container["HF Space container :7860"]Gunicorn[gunicorn<br/>2 workers]WN[WhiteNoise<br/>middleware]DRF[DRF views<br/>api/views/]SPA[(SPA dist/<br/>index.html and assets)]Stat[(staticfiles/<br/>collectstatic)]CK[(/app/checkpoints<br/>PyTorch weights)]Research[(/app/research<br/>research code)]endHub[(HF Hub<br/>bani57/checkpoints)]Browser -->|HTTPS| GunicornGunicorn --> WN2 unmodified linesWN -->|miss| URLs{Django<br/>URL router}URLs -->|/api/v1/*| DRFURLs -->|non-API path| SPADRF -.->|imports| ResearchDRF -.->|loads weights| CKCK -.->|cold-start populate| Hub```Routing precedence inside the container:18 unmodified lines## ConcurrencyFree-tier HF Spaces run on 2 vCPU with no GPU. The container starts gunicorn with two workers and two threads, and `ModelRegistry._inference_lock` serializes inference globally. A second concurrent inference request gets HTTP 429 with `INFERENCE_BUSY`. Discovery endpoints (datasets, entities, methods, health) acquire no lock and run freely in parallel.## Container lifecycle5 unmodified linesparticipant G as gunicornparticipant D as Django (AppConfig.ready)HF->>E: container startE->>Hub: snapshot_download(bani57/checkpoints)Hub-->>E: 5.4 GB into /app/checkpointsE->>G: exec gunicorn :7860G->>D: import research_api.wsgiD->>D: ModelRegistry.initialize()D->>D: scan checkpoint dirs10 unmodified lines.βββ Dockerfile # multi-stage: Node SPA build β micromamba runtimeβββ environment.yml # conda half (rdkit 2023.03.2, boost, cairo, β¦)βββ docker-compose.yml # local-dev parity, named volume for checkpointsβββ entrypoint.sh # snapshot_download then exec gunicornβββ README.md # HF Space landing card (YAML front-matter)βββ src/β βββ backend/4 unmodified linesβ βββ frontend/ # Vue 3 SPA (built into dist/ at image time)β βββ research/ # research code, imported via sys.path tweaksβββ scripts/βββ upload_checkpoints.py # one-shot publisher to bani57/checkpoints```## Cross-references8 unmodified lines9101112131415161718192021222 unmodified lines252627282930313218 unmodified lines515253545556575859606162635 unmodified lines69707172737475767710 unmodified lines88899091929394954 unmodified lines1001011021031041051068 unmodified linesflowchart LRBrowser([Browser])subgraph Container["HF Space container :7860"]Gunicorn[gunicorn master<br/>1 worker, 4 threads<br/>--preload]WN[WhiteNoise<br/>middleware]DRF[DRF views<br/>api/views/]SPA[(SPA dist/<br/>index.html and assets)]Stat[(staticfiles/<br/>collectstatic)]Research[(/app/research<br/>code, configs,<br/>Loader caches,<br/>HF-Hub weights)]endHub[(HF Hub<br/>Bani57/checkpoints)]Browser -->|HTTPS| GunicornGunicorn --> WN2 unmodified linesWN -->|miss| URLs{Django<br/>URL router}URLs -->|/api/v1/*| DRFURLs -->|non-API path| SPADRF -.->|imports + loads| ResearchResearch -.->|cold-start populate| Hub```Routing precedence inside the container:18 unmodified lines## ConcurrencyFree-tier HF Spaces run on 2 vCPU with no GPU. The container starts gunicorn with **one preloaded worker** and four threads. The single-worker choice is deliberate:- The `ModelRegistry` holds multi-GB of COINs Loaders + lazily-loaded model weights in process RAM. A second worker would duplicate every byte.- `ModelRegistry._inference_lock` serializes inference globally. A second worker would only ever queue on the same lock β no throughput gain.- `--preload` runs Django setup (and `ModelRegistry.initialize`) once in the master before forking, so the worker inherits a ready state via copy-on-write and gunicorn's silent-time timeout doesn't fire mid-init.A second concurrent inference request gets HTTP 429 with `INFERENCE_BUSY`. Discovery endpoints (datasets, entities, methods, health) acquire no lock and run freely in parallel via the worker's threads.## Container lifecycle5 unmodified linesparticipant G as gunicornparticipant D as Django (AppConfig.ready)HF->>E: container startE->>Hub: snapshot_download(Bani57/checkpoints)Hub-->>E: 5.4 GB into /app/researchE->>G: exec gunicorn --preload :7860G->>D: import research_api.wsgiD->>D: ModelRegistry.initialize()D->>D: scan checkpoint dirs10 unmodified lines.βββ Dockerfile # multi-stage: Node SPA build β micromamba runtimeβββ environment.yml # conda half (rdkit 2023.03.2, boost, cairo, β¦)βββ docker-compose.yml # local-dev parity (no volume β checkpoints re-pull on each up)βββ entrypoint.sh # snapshot_download then exec gunicorn --preloadβββ README.md # HF Space landing card (YAML front-matter)βββ src/β βββ backend/4 unmodified linesβ βββ frontend/ # Vue 3 SPA (built into dist/ at image time)β βββ research/ # research code, imported via sys.path tweaksβββ scripts/βββ upload_checkpoints.py # one-shot publisher to Bani57/checkpoints```## Cross-references
3 unmodified lines4567891011121314151617181920212223242526 unmodified lines52535455565717 unmodified lines7576777879803 unmodified lines## Boot sequence`api/apps.ApiConfig.ready()` runs once when Django imports the app β before gunicorn accepts traffic. It calls `ModelRegistry.initialize()`, which executes four steps in order:```mermaidflowchart TBStart([AppConfig.ready]) --> Skip{outer auto-reloader?}Skip -->|yes| Done([return])Skip -->|no| Init[ModelRegistry.initialize]Init --> DL[_download_checkpoints<br/>HF Hub snapshot_download]DL --> Scan[_scan_checkpoints<br/>list available files]Scan --> Loaders[_load_all_loaders<br/>3 lightweight Loaders]Loaders --> Sub[_generate_sample_subgraphs<br/>per-dataset DFS partitions]Sub --> Ready([gunicorn accepts traffic])```### 1. Download checkpoints (idempotent)`_download_checkpoints` checks every expected subdir under `CHECKPOINTS_ROOT`; if any is empty it calls `huggingface_hub.snapshot_download(repo_id="bani57/checkpoints")` to pull the missing files. The repo's directory layout mirrors the on-disk one, so files land in their final location and the scan code doesn't need a redistribution step.In production the `entrypoint.sh` script also calls `snapshot_download` *before* gunicorn starts. That makes Django's call a no-op on a normal cold start; it only does real work when run outside the container or when the entrypoint was bypassed.26 unmodified linesThe COINs registry also reuses Loaders across algorithms via `_coins_loaders[(dataset_id, seed, leiden_resolution)]`: all four `transe / distmult / complex / rotate` checkpoints on a dataset share the same seed and Leiden resolution, so they share one Loader and don't reload the graph four times.## Concurrency and the inference lock`ModelRegistry._inference_lock` is a single `threading.Lock`. Every endpoint that runs PyTorch inference acquires it non-blocking; if it can't, it raises `InferenceBusy` (HTTP 429). The lock is released in a `finally` after the response is fully streamed:17 unmodified linesWorst case (everything ever requested in one Space lifetime): well under 16 GB. The current code does not evict β caches grow monotonically until the container restarts.## Cross-references- [explanation/architecture.md](architecture.md) β where this lifecycle sits in the request flow.3 unmodified lines456789101112131415161718192021222324252627282926 unmodified lines5657585960616263646566676817 unmodified lines86878889909192939495969798991001011021031041051061071083 unmodified lines## Boot sequence`api/apps.ApiConfig.ready()` runs once when Django imports the app β typically inside the gunicorn master under `--preload`, before any worker forks. It calls `ModelRegistry.initialize()`, which executes four steps in order:```mermaidflowchart TBStart([AppConfig.ready]) --> Mgmt{argv in<br/>SKIP_REGISTRY_INIT?}Mgmt -->|yes: collectstatic,<br/>migrate, check, β¦| Done([return])Mgmt -->|no| Skip{outer auto-reloader?}Skip -->|yes| DoneSkip -->|no| Init[ModelRegistry.initialize]Init --> DL[_download_checkpoints<br/>HF Hub snapshot_download]DL --> Scan[_scan_checkpoints<br/>list available files]Scan --> Loaders[_load_all_loaders<br/>3 lightweight Loaders]Loaders --> Sub[_generate_sample_subgraphs<br/>per-dataset DFS partitions]Sub --> Ready([gunicorn worker forks via copy-on-write])```The `SKIP_REGISTRY_INIT` set covers `collectstatic`, `migrate`, `makemigrations`, `check`, `shell`, `test`, etc. Without that guard, `python manage.py collectstatic --noinput` at image build time would trigger the full ~6 GB checkpoint download into a throwaway layer.### 1. Download checkpoints (idempotent)`_download_checkpoints` checks every expected subdir under `CHECKPOINTS_ROOT`; if any is empty it calls `huggingface_hub.snapshot_download(repo_id="Bani57/checkpoints")` to pull the missing files. The repo's directory layout mirrors the on-disk one, so files land in their final location and the scan code doesn't need a redistribution step.In production the `entrypoint.sh` script also calls `snapshot_download` *before* gunicorn starts. That makes Django's call a no-op on a normal cold start; it only does real work when run outside the container or when the entrypoint was bypassed.26 unmodified linesThe COINs registry also reuses Loaders across algorithms via `_coins_loaders[(dataset_id, seed, leiden_resolution)]`: all four `transe / distmult / complex / rotate` checkpoints on a dataset share the same seed and Leiden resolution, so they share one Loader and don't reload the graph four times.### Monkey-patches around `experiment.prepare()`Two patches wrap each call to `experiment.prepare()` in `_load_coins_experiment`, restored in a `finally`:- **`Module.share_memory` β no-op.** The research code's `prepare()` calls `embedder.share_memory()` to share weights across multi-process training workers. Inference is single-process; the call is gratuitous, and on Linux containers with a small `/dev/shm` (Docker default 64 MB, free HF Spaces tmpfs similar) it raises a `Bus error` mid-prepare. The no-op makes `prepare()` return cleanly.- **`torch.load` β TransE-init dim expansion.** `prepare()` loads `transe_model.tar` to seed the embedder's `entity_embeddings_initial` buffers. The KBGAT embedder's `__init__` then assigns `weight.data = init`, which silently re-shapes the YAML-declared embedding layer to the init's shape. For wordnet KBGAT this is fatal: the trained checkpoint was 200d but the wordnet TransE init is 100d, so the embedder ends up at 100d and the trained `load_state_dict` blows up on the dim mismatch. The patch detects TransE state dicts being loaded and repeats them along the embedding axis (e.g. 100d β 200d via `cat([init, init])`) when the YAML's `embedding_dim` is an integer multiple of the init's dim β same trick `_adapt_kbgat_state_dict` already uses for the GATConv multi-head expansion.## Concurrency and the inference lock`ModelRegistry._inference_lock` is a single `threading.Lock`. Every endpoint that runs PyTorch inference acquires it non-blocking; if it can't, it raises `InferenceBusy` (HTTP 429). The lock is released in a `finally` after the response is fully streamed:17 unmodified linesWorst case (everything ever requested in one Space lifetime): well under 16 GB. The current code does not evict β caches grow monotonically until the container restarts.### Local-dev memory floorLoading all three Loaders + computing graph metrics for NELL peaks at ~5β6 GB transient RAM unless the bundled Loader caches (`results/<dataset>/*.npz` and `*.gz`, ~10 MB total in the image) are present, which let the boot read precomputed arrays instead of recomputing them. WSL2 should be configured for at least 12 GB to give Docker enough headroom; the recommended `.wslconfig` is:```ini[wsl2]memory=12GBprocessors=4swap=4GB````docker-compose.yml` also sets `shm_size: "2gb"` to avoid `Bus error` from PyTorch's shared-memory paths under Docker's 64 MB `/dev/shm` default.## MultiProx symmetry safeguard`graphgen_inference._collapse_final` symmetrises the edge tensor before calling `model.sample_discrete_graph_given_z0`. The model has a strict `assert (pred_E == pred_E.T).all()`; the MultiProx Gibbs aggregation (mean / median over multiple chains) can introduce ULP-level asymmetry that survives into `pred_E` and trips the assert on some BLAS / vectorization stacks (notably the Linux `+cu118` torch wheel inside the deployment container, while the same code runs fine on the Windows wheel in dev). `E = (E + E.T) / 2` is a no-op on already-symmetric input and a one-line invariant fix when it isn't.## Cross-references- [explanation/architecture.md](architecture.md) β where this lifecycle sits in the request flow.
63 unmodified lines6465666768697071727363 unmodified lines## Deployment### HF SpaceA Hugging Face Spaces application running this repo's `Dockerfile`. The deployed URL is `https://bani57-website.hf.space`. The Space repo is `bani57/website`.### HF Hub model repo`bani57/checkpoints` β holds all PyTorch weights. Mirrors the on-disk layout under `CHECKPOINTS_ROOT` so `huggingface_hub.snapshot_download` populates files in their expected paths and the registry's scan logic finds them unchanged.### Persistent storage (HF Spaces)A paid `/data` volume that survives Space restarts. Free Spaces have 50 GB ephemeral disk that resets on restart. Without persistent storage, every cold start re-downloads checkpoints from HF Hub.63 unmodified lines6465666768697071727363 unmodified lines## Deployment### HF SpaceA Hugging Face Spaces application running this repo's `Dockerfile`. The deployed URL is `https://bani57-website.hf.space`. The Space repo is `Bani57/website`.### HF Hub model repo`Bani57/checkpoints` β holds all PyTorch weights. Mirrors the on-disk layout under `CHECKPOINTS_ROOT` so `huggingface_hub.snapshot_download` populates files in their expected paths and the registry's scan logic finds them unchanged.### Persistent storage (HF Spaces)A paid `/data` volume that survives Space restarts. Free Spaces have 50 GB ephemeral disk that resets on restart. Without persistent storage, every cold start re-downloads checkpoints from HF Hub.
12345678910111223 unmodified lines3637383940414232 unmodified lines7576777879808110 unmodified lines929394959697984 unmodified lines103104105106107108109# How to deploy to Hugging Face SpacesPush a new version of the site to the HF Space `bani57/website`. Everything is git-based β there is no build button. The Space rebuilds its Docker image from whatever is on the `main` branch of its repo. For the rationale and full design see [`plans/deploy_huggingface_spaces.md`](../../plans/deploy_huggingface_spaces.md).## Prerequisites- The Space `bani57/website` exists with **SDK = Docker**, **Hardware = CPU basic (free)**.- Space secrets are set: `DJANGO_SECRET_KEY`, `DJANGO_DEBUG=False`, `DJANGO_ALLOWED_HOSTS=bani57-website.hf.space`.- The HF Hub model repo `bani57/checkpoints` exists and contains the current weights. See [Refreshing checkpoints](#refreshing-checkpoints) below.- Local working tree is on the deployment branch (typically `master`) and tests pass.## 1. Local container smoke test23 unmodified linesAdd the HF git remote (one-time):```bashgit remote add hf https://huggingface.co/spaces/bani57/website```Then for each release:32 unmodified lines## Refreshing checkpointsCheckpoints live in `bani57/checkpoints` on HF Hub, separate from the code repo. To publish new weights:```bashhuggingface-cli login # one-time, paste a write token10 unmodified lines- **Secrets** (encrypted, not exposed in logs):- `DJANGO_SECRET_KEY` β required. Generate with `python -c "import secrets; print(secrets.token_urlsafe(50))"`.- `HF_TOKEN` β only if `bani57/checkpoints` is private.- **Variables** (visible in logs and to viewers of the Space metadata):- `DJANGO_DEBUG=False`.- `DJANGO_ALLOWED_HOSTS=bani57-website.hf.space`.4 unmodified lines## Optional: persistent storageFree Spaces have 50 GB ephemeral disk that resets on restart, so every cold start re-downloads ~5.4 GB of checkpoints. The first request after a restart waits for `snapshot_download` to finish. For ~$5/month, the Space's **Persistent Storage** tier puts `/data` on a permanent volume; mount the checkpoints there (set `CHECKPOINTS_ROOT=/data/checkpoints`) and cold starts become instant. Worth doing only when traffic justifies it.## See also12345678910111223 unmodified lines3637383940414232 unmodified lines7576777879808110 unmodified lines929394959697984 unmodified lines103104105106107108109# How to deploy to Hugging Face SpacesPush a new version of the site to the HF Space `Bani57/website`. Everything is git-based β there is no build button. The Space rebuilds its Docker image from whatever is on the `main` branch of its repo. For the rationale and full design see [`plans/deploy_huggingface_spaces.md`](../../plans/deploy_huggingface_spaces.md).## Prerequisites- The Space `Bani57/website` exists with **SDK = Docker**, **Hardware = CPU basic (free)**.- Space secrets are set: `DJANGO_SECRET_KEY`, `DJANGO_DEBUG=False`, `DJANGO_ALLOWED_HOSTS=bani57-website.hf.space`.- The HF Hub model repo `Bani57/checkpoints` exists and contains the current weights. See [Refreshing checkpoints](#refreshing-checkpoints) below.- Local working tree is on the deployment branch (typically `master`) and tests pass.## 1. Local container smoke test23 unmodified linesAdd the HF git remote (one-time):```bashgit remote add hf https://huggingface.co/spaces/Bani57/website```Then for each release:32 unmodified lines## Refreshing checkpointsCheckpoints live in `Bani57/checkpoints` on HF Hub, separate from the code repo. To publish new weights:```bashhuggingface-cli login # one-time, paste a write token10 unmodified lines- **Secrets** (encrypted, not exposed in logs):- `DJANGO_SECRET_KEY` β required. Generate with `python -c "import secrets; print(secrets.token_urlsafe(50))"`.- `HF_TOKEN` β strongly recommended. A read-scope token (huggingface.co/settings/tokens β New token β Read) lifts anonymous rate limits and roughly triples checkpoint download throughput on cold starts. Required only if the checkpoint repo is private.- **Variables** (visible in logs and to viewers of the Space metadata):- `DJANGO_DEBUG=False`.- `DJANGO_ALLOWED_HOSTS=bani57-website.hf.space`.4 unmodified lines## Optional: persistent storageFree Spaces have 50 GB ephemeral disk that resets on restart, so every cold start re-downloads ~5.4 GB of checkpoints. The first request after a restart waits for `snapshot_download` to finish. For ~$5/month, the Space's **Persistent Storage** tier puts `/data` on a permanent volume. To use it, set the variable `CHECKPOINTS_ROOT=/data/checkpoints` in the Space settings. The container's `entrypoint.sh` will write the snapshot there; subsequent restarts find it already populated. The default unifies `CHECKPOINTS_ROOT` with `RESEARCH_ROOT=/app/research`, so checkpoints land alongside the bundled research code on free tier β clean for one-shot deploys, costly to re-pull on every restart.## See also
7 unmodified lines89101112139 unmodified lines2324252627282930313233347 unmodified lines- Node 20+ and npm.- ~6 GB of free disk for the checkpoints if you intend to run inference locally.- Optional: a Hugging Face account if you want to publish or update checkpoints.## 1. Create the Python environment9 unmodified lines## 2. Pull checkpointsIf you have a Hugging Face account and the `bani57/checkpoints` repo is accessible to you:```bashhuggingface-cli login # paste a read tokenpython -c "from huggingface_hub import snapshot_download; \snapshot_download(repo_id='bani57/checkpoints', \local_dir='src/research', local_dir_use_symlinks=False)"```7 unmodified lines891011121314151617181920219 unmodified lines3132333435363738394041427 unmodified lines- Node 20+ and npm.- ~6 GB of free disk for the checkpoints if you intend to run inference locally.- Optional: a Hugging Face account if you want to publish or update checkpoints.- For Docker (`docker compose up`): WSL2 with at least **12 GB** of memory. Bumping `/dev/shm` is handled by `docker-compose.yml` (`shm_size: "2gb"`). Edit `%UserProfile%\.wslconfig`:```ini[wsl2]memory=12GBprocessors=4swap=4GB```then `wsl --shutdown` and restart Docker Desktop. The peak boot RAM is ~5β6 GB while the three COINs Loaders compute graph metrics.## 1. Create the Python environment9 unmodified lines## 2. Pull checkpointsIf you have a Hugging Face account and the `Bani57/checkpoints` repo is accessible to you:```bashhuggingface-cli login # paste a read tokenpython -c "from huggingface_hub import snapshot_download; \snapshot_download(repo_id='Bani57/checkpoints', \local_dir='src/research', local_dir_use_symlinks=False)"```
12 unmodified lines1314151617181983 unmodified lines1031041051061071084 unmodified lines11311411511611711812 unmodified lines## `api/` β Django app### `apps.py``ApiConfig.ready()` runs once at boot. Skips initialization in the outer `runserver` reloader process (avoids double-loading models in dev) and calls `ModelRegistry.initialize()` in the inner one.### `urls.py`Maps every endpoint listed in [reference/api.md](api.md) to the matching view class.83 unmodified lines- `_adapt_shape_mismatches`, `_adapt_mlp_bn_keys`, `_adapt_kbgat_state_dict` β torch-geometric 2.0.x β 2.3.x weight-format compatibility shims.- `_free_heavy_arrays` β discards memory-intensive Loader fields after init.### `coins_inference.py``coins_predict_inner(experiment, dataset_id, algorithm, query_structure_id, anchors, variables, relations_map, top_k)` β runs a single COINs prediction. Validates the query, builds the embedding query, scores candidate tails, returns the top-k with cleaned names and the community-rank info.4 unmodified lines- `run_multiprox_init(model, num_nodes, n, m, t, t_prime, gibbs_chain_freq, dataset_id)` β initial denoise to step `t_prime`. Returns the partial state for a `/continue` follow-up.- `run_multiprox_step(model, state, dataset_id)` β one Gibbs round.- `encode_state_blob` / `decode_state_blob` β base64 round-trip for the [continuation token](../glossary.md#continuation-token--state-blob).### `kg_anomaly_inference.py`The KG-subgraph correction loop. Mirrors `graphgen_inference.py` but operates on knowledge-graph subgraphs and computes the KG log-likelihood metric per frame using the frozen COINs link ranker.12 unmodified lines1314151617181920212283 unmodified lines1061071081091101111121131141151164 unmodified lines12112212312412512612712 unmodified lines## `api/` β Django app### `apps.py``ApiConfig.ready()` runs once at boot. Two skip-checks before calling `ModelRegistry.initialize()`:- `sys.argv[1]` against `_SKIP_REGISTRY_INIT` (`collectstatic`, `migrate`, `makemigrations`, `check`, `shell`, `showmigrations`, `diffsettings`, `test`, `compilemessages`, `makemessages`). Stops `python manage.py collectstatic --noinput` from triggering a multi-GB checkpoint download into a throwaway image layer.- The outer `runserver` reloader process (`RUN_MAIN != "true"`). Stops dev mode from doing the heavy boot twice.### `urls.py`Maps every endpoint listed in [reference/api.md](api.md) to the matching view class.83 unmodified lines- `_adapt_shape_mismatches`, `_adapt_mlp_bn_keys`, `_adapt_kbgat_state_dict` β torch-geometric 2.0.x β 2.3.x weight-format compatibility shims.- `_free_heavy_arrays` β discards memory-intensive Loader fields after init.`_load_coins_experiment` wraps each `experiment.prepare()` call in two monkey-patches (restored in a `finally`) β see [explanation/inference-lifecycle.md](../explanation/inference-lifecycle.md#monkey-patches-around-experimentprepare) for the rationale:- `Module.share_memory` β no-op (avoids `Bus error` from PyTorch shared-memory paths under tight `/dev/shm`).- `torch.load` β TransE-init dim expansion (repeats `transe_model.tar` weights along the embedding axis when YAML's `embedding_dim` is an integer multiple of the init's dim, so KBGAT's `weight.data = init` doesn't clobber the model's declared dim).### `coins_inference.py``coins_predict_inner(experiment, dataset_id, algorithm, query_structure_id, anchors, variables, relations_map, top_k)` β runs a single COINs prediction. Validates the query, builds the embedding query, scores candidate tails, returns the top-k with cleaned names and the community-rank info.4 unmodified lines- `run_multiprox_init(model, num_nodes, n, m, t, t_prime, gibbs_chain_freq, dataset_id)` β initial denoise to step `t_prime`. Returns the partial state for a `/continue` follow-up.- `run_multiprox_step(model, state, dataset_id)` β one Gibbs round.- `encode_state_blob` / `decode_state_blob` β base64 round-trip for the [continuation token](../glossary.md#continuation-token--state-blob).- `_collapse_final` symmetrises `E` (`E = (E + E.T) / 2`) before calling `model.sample_discrete_graph_given_z0`. The model has a strict symmetry assert that's tripped by ULP-level drift from the MultiProx aggregation on some BLAS stacks. See the [MultiProx symmetry safeguard](../explanation/inference-lifecycle.md#multiprox-symmetry-safeguard) note.### `kg_anomaly_inference.py`The KG-subgraph correction loop. Mirrors `graphgen_inference.py` but operates on knowledge-graph subgraphs and computes the KG log-likelihood metric per frame using the frozen COINs link ranker.
27 unmodified lines2829303132333432 unmodified lines676869707172737475762 unmodified lines798081828384855 unmodified lines919293949596971 unmodified line991001011021031041053 unmodified lines10911011111211311411527 unmodified lines```3. **Model checkpoints** β downloaded automatically from the Hugging Face Hub model repo`bani57/checkpoints` on first boot. The remote layout mirrors the on-disk one, so`huggingface_hub.snapshot_download(local_dir=CHECKPOINTS_ROOT)` drops files directlyinto the expected paths:- `src/research/COINs-KGGeneration/graph_completion/checkpoints/` (COINs: `{dataset}_{algorithm}.tar`)32 unmodified lines| `DJANGO_ALLOWED_HOSTS` | `localhost,127.0.0.1` | Comma-separated allowed hosts. || `CORS_ALLOWED_ORIGINS` | `https://bani57-website.hf.space` | Comma-separated allowed CORS origins. || `TORCH_DEVICE` | Auto (`cuda:0` if available, else `cpu`) | PyTorch device for model inference. || `RESEARCH_ROOT` | `<repo>/src/research` | Where the research-code modules live. || `CHECKPOINTS_ROOT` | Same as `RESEARCH_ROOT` | Where `huggingface_hub` deposits weights. In the container this is `/app/checkpoints` on a writable volume. || `HF_CHECKPOINTS_REPO` | `bani57/checkpoints` | HF Hub model repo holding all weights. || `HF_TOKEN` | unset | Only needed if the checkpoint repo is private. || `SPA_DIST_DIR` | `<backend>/dist` | Folder containing `index.html` from `npm run build`. WhiteNoise serves assets from here. |## Startup Sequence2 unmodified linesfrom the Hugging Face Hub *before* gunicorn starts, so workers never block on thenetwork. Then on Django boot (`ApiConfig.ready()`), the `ModelRegistry` initializes:1. **Verify / download checkpoints** from `bani57/checkpoints` on HF Hub if any expectedsubdir is missing. Idempotent β a no-op when the entrypoint already populated the treeor when running locally with weights on disk.2. **Scan checkpoint directories** to detect available models per method5 unmodified lines## DeploymentThe site is packaged as a single Docker image and deployed to a Hugging Face Space(`bani57/website` -> <https://bani57-website.hf.space>). The image:- builds the Vue SPA with `npm run build` in a Node 20 stage,- assembles a `mambaorg/micromamba` runtime mirroring the local `website_c` env from1 unmodified line- copies the SPA `dist/` next to Django so WhiteNoise serves it on the same origin as`/api/v1/`,- runs `entrypoint.sh`, which `snapshot_download`s checkpoints from`bani57/checkpoints` on HF Hub into `/app/checkpoints` and execs `gunicorn` on `0.0.0.0:7860`.Local reproduction:```bash3 unmodified linesPush to the Space (one-time remote setup):```bashgit remote add hf https://huggingface.co/spaces/bani57/websitegit push hf master:main```27 unmodified lines2829303132333432 unmodified lines67686970717273747576772 unmodified lines808182838485865 unmodified lines929394959697981 unmodified line1001011021031041051063 unmodified lines11011111211311411511627 unmodified lines```3. **Model checkpoints** β downloaded automatically from the Hugging Face Hub model repo`Bani57/checkpoints` on first boot. The remote layout mirrors the on-disk one, so`huggingface_hub.snapshot_download(local_dir=CHECKPOINTS_ROOT)` drops files directlyinto the expected paths:- `src/research/COINs-KGGeneration/graph_completion/checkpoints/` (COINs: `{dataset}_{algorithm}.tar`)32 unmodified lines| `DJANGO_ALLOWED_HOSTS` | `localhost,127.0.0.1` | Comma-separated allowed hosts. || `CORS_ALLOWED_ORIGINS` | `https://bani57-website.hf.space` | Comma-separated allowed CORS origins. || `TORCH_DEVICE` | Auto (`cuda:0` if available, else `cpu`) | PyTorch device for model inference. || `RESEARCH_ROOT` | `<repo>/src/research` (dev), `/app/research` (image) | Where the research-code modules live. || `CHECKPOINTS_ROOT` | Same as `RESEARCH_ROOT` | Where `huggingface_hub` deposits weights. Override to e.g. `/data/checkpoints` on a paid HF Space with persistent storage. || `HF_CHECKPOINTS_REPO` | `Bani57/checkpoints` | HF Hub model repo holding all weights. || `HF_TOKEN` | unset | Recommended. Read-scope token lifts anonymous rate limits and roughly triples cold-start download throughput. Required if the repo is private. Empty values are unset by `entrypoint.sh` to avoid a malformed `Bearer ` header. || `HF_HUB_ENABLE_HF_TRANSFER` | `1` (image), unset (dev) | Enables the Rust-accelerated `hf_transfer` backend for `snapshot_download`. || `SPA_DIST_DIR` | `<backend>/dist` | Folder containing `index.html` from `npm run build`. WhiteNoise serves assets from here. |## Startup Sequence2 unmodified linesfrom the Hugging Face Hub *before* gunicorn starts, so workers never block on thenetwork. Then on Django boot (`ApiConfig.ready()`), the `ModelRegistry` initializes:1. **Verify / download checkpoints** from `Bani57/checkpoints` on HF Hub if any expectedsubdir is missing. Idempotent β a no-op when the entrypoint already populated the treeor when running locally with weights on disk.2. **Scan checkpoint directories** to detect available models per method5 unmodified lines## DeploymentThe site is packaged as a single Docker image and deployed to a Hugging Face Space(`Bani57/website` -> <https://bani57-website.hf.space>). The image:- builds the Vue SPA with `npm run build` in a Node 20 stage,- assembles a `mambaorg/micromamba` runtime mirroring the local `website_c` env from1 unmodified line- copies the SPA `dist/` next to Django so WhiteNoise serves it on the same origin as`/api/v1/`,- runs `entrypoint.sh`, which `snapshot_download`s checkpoints from`Bani57/checkpoints` on HF Hub into `/app/checkpoints` and execs `gunicorn` on `0.0.0.0:7860`.Local reproduction:```bash3 unmodified linesPush to the Space (one-time remote setup):```bashgit remote add hf https://huggingface.co/spaces/Bani57/websitegit push hf master:main```