fix(deploy): bind port immediately and warm up models in background
Andrej Janchevski
93b17d3
HF Spaces marked the container unhealthy ("Launch timed out, workload
was not healthy after 30 min") because gunicorn only bound :7860 after
the checkpoint download and the --preload ModelRegistry init (COINs
graph metrics) had finished.
- entrypoint.sh: drop the blocking snapshot_download pre-warm and
--preload; exec gunicorn straight away
- ModelRegistry.start_background_initialize() runs initialize() in a
daemon thread from ApiConfig.ready(); get() raises 503
MODEL_UNAVAILABLE until ready
- /health always returns 200 with status ok | warming_up | error and a
warmup progress object
- frontend: WarmupBanner polls /health and shows a loading state;
apiError reads the error envelope; SystemStatus reads models_loaded
- docs: backend README, api.yaml, architecture / lifecycle docs
fix(coins): score full hit community instead of only valid answers
Andrej Janchevski
2d03843
Step 2 used to filter candidate entities to the set returned by
get_all_answers, so the link ranker only ever scored entities already
known to satisfy the query. Top-K therefore showed at most one row when
a community had a single valid answer, and the reported speedup hid the
fact that the model was not actually discriminating against negatives.
Now Step 2 mirrors rank_samples (experiments.py:782-786): the hit
community is the first one in step-1 order containing any valid answer,
and we score every entity in it minus the anchors. Predictions carry an
is_valid_answer flag so the UI can mark genuine hits with a check icon.
Scoring is mini-batched at 512 to bound CPU memory on large communities.
The OpenAPI CoinsPrediction schema gains the required is_valid_answer
boolean to keep clients in sync.
docs(deploy): refresh for the post-launch deployment iteration
Andrej Janchevski
5ed6f37
Captures 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).
fix(deploy): harden container runtime and unify research / checkpoint roots
Andrej Janchevski
5375c2e
Multiple production-launch fixes that fall under "make the container
actually start and stay up reliably".
settings.py + Dockerfile: unify CHECKPOINTS_ROOT with RESEARCH_ROOT
(/app/research). The earlier split (CHECKPOINTS_ROOT=/app/checkpoints
on a named volume) caused a path mismatch — configs and Loader caches
live with the bundled research code under RESEARCH_ROOT, while
HF-Hub-downloaded weights landed in CHECKPOINTS_ROOT, breaking the
COINs experiment loader's lookups (e.g. configs/freebase.yml).
Snapshot_download now writes alongside the bundled tree; on paid HF
Spaces with persistent storage, override CHECKPOINTS_ROOT to /data.
Also moves the RESEARCH_ROOT definition above the sys.path additions
so the in-image /app/research path is honoured.
entrypoint.sh: switch gunicorn to one preloaded worker with four
threads and a 1800s timeout. --preload runs ModelRegistry.initialize
in the master before forking, so workers inherit a ready state via
copy-on-write and gunicorn's silen…
build(deps): add transitive research deps and rust-accelerated transfer
Andrej Janchevski
ce3d8f2
The COINs research code transitively imports a chunk of packages that
were missing from requirements.txt — silently filled in by manual
pip-installs in the local mamba env, but absent from the deployment
image. Each one surfaced as a ModuleNotFoundError at gunicorn boot:
- seaborn — graph_analysis/metrics.py top-level import
- karateclub, gensim, python-louvain — community detection paths
- PyMetis, PyGSP — graph partitioning + signal processing
- compress-pickle — graph_data/serialization.py
- python-Levenshtein, six, decorator — karateclub transitive
- tensorboardX — research code logging hooks
- torch-scatter — torch_geometric op fallbacks (PyG wheel index)
Also bumps numpy from 1.23 to 1.26.* (matches the verified-working
local env; the older pin clashed with karateclub's overly-strict and
runtime-incorrect numpy<1.23 cap), and adds hf_transfer to enable
HF_HUB_ENABLE_HF_TRANSFER=1 for ~3x faster cold-start downloads.
fix(coins): wrap experiment.prepare() with shm and dim-expansion patches
Andrej Janchevski
15144da
Two research-code behaviours break inference inside the deployment
container; both are silenced by monkey-patching for the duration of
each experiment.prepare() call (and restored in a finally).
- torch.nn.Module.share_memory: research code calls
embedder.share_memory() to share weights across multi-process
training workers. The website is single-process and the call is
gratuitous; on Linux containers with a small /dev/shm (Docker
default 64 MB, free HF Spaces tmpfs similar) it raises Bus error
mid-prepare. No-op replacement keeps prepare() happy.
- torch.load: prepare() loads transe_model.tar to seed the embedder's
entity_embeddings_initial buffers, then KBGAT's __init__ assigns
weight.data = init, silently re-shaping the YAML-declared embedding
layer to the init's shape. For wordnet KBGAT this is fatal: the
trained checkpoint is 200d but the wordnet TransE init is 100d, so
the embedder ends up at 100d and load_state_dict fails on the
trained weights. The p…
fix(backend): skip ModelRegistry init for django management commands
Andrej Janchevski
b598a6a
ApiConfig.ready() runs for every Django invocation, including
collectstatic at image build time. Without a guard, that triggers
ModelRegistry.initialize() -> _download_checkpoints (~6 GB from HF
Hub) into a throwaway image layer, then loads three Loaders + builds
sample subgraphs — adding 15+ minutes to every docker build for no
benefit.
Adds _SKIP_REGISTRY_INIT covering collectstatic, migrate,
makemigrations, check, shell, showmigrations, diffsettings, test,
compilemessages, makemessages. Existing runserver auto-reloader
guard kept intact for dev parity.
fix(graphgen): symmetrize E before final discrete-graph collapse
Andrej Janchevski
221db87
The MultiProx Gibbs aggregation (mean / median over multiple chains)
introduces ULP-level asymmetry into the edge tensor 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. model.sample_discrete_graph_given_z0() then trips on
its strict assert (pred_E == pred_E.T).all() and the SSE stream errors
out before the multiprox preview can be returned.
E = (E + E.T) / 2 in _collapse_final is a no-op on already-symmetric
input and a one-line invariant fix when ULP drift breaks symmetry.
docs: add technical documentation set
Andrej Janchevski
175b650
Lays out a docs/ tree in Diataxis layout and rewires the three
README files (top-level, src/backend, src/frontend) as thin routing
layers that delegate the depth to docs/.
- docs/glossary.md owns every domain term (COINs, MultiProxAn, query
structure, SSE, inference lock, state blob, HF Space, …); other
docs link in on first mention rather than redefining.
- docs/explanation/{architecture,research-methods,inference-lifecycle}.md
cover container topology, what each demo computes scientifically,
and the boot/lazy-load/lock sequence. Mermaid diagrams for the
request flow and container lifecycle.
- docs/reference/{api,sse-protocol,backend-services,frontend-modules}.md
describe endpoints, the streaming wire format, every Python service
module, and every frontend store / composable / component group.
- docs/guides/{local-development,deploy}.md walk through setting up
website_c locally and publishing a release to the HF Space (with
Space secrets, checkpoint refresh, and ro…
feat(frontend): use relative API base URL for same-origin deploy
Andrej Janchevski
9b94c0c
- .env.production: VITE_API_BASE_URL is now empty, so the SPA hits
the same origin as the page it was served from.
- client.js, useSseStream.js: switch || to ?? so an explicitly empty
env value survives instead of falling back to the localhost dev URL.
Pairs with the backend's new same-origin SPA serving via WhiteNoise:
the deployed container exposes both the SPA and /api/v1/ on a single
hf.space URL, so no CORS dance is needed in production.
feat(backend): rewire for hugging face spaces deployment
Andrej Janchevski
cb5f524
- registry.py: replace gdown / Google Drive with
huggingface_hub.snapshot_download from bani57/checkpoints. The
remote layout mirrors the on-disk one under CHECKPOINTS_ROOT, so the
scan logic finds files unchanged and the old _distribute_checkpoints
step is gone.
- settings.py: env-drive ALLOWED_HOSTS, CORS_ALLOWED_ORIGINS,
RESEARCH_ROOT and CHECKPOINTS_ROOT so dev (local repo paths) and
prod (writable /app/checkpoints) share one settings file. Add
whitenoise + django.contrib.staticfiles for same-origin SPA
serving via SPA_DIST_DIR / WHITENOISE_ROOT, plus SecurityMiddleware,
CsrfViewMiddleware and XFrameOptionsMiddleware (deploy-check
hygiene). HSTS / secure cookies / CSRF_TRUSTED_ORIGINS gated on
DEBUG=False; SECURE_SSL_REDIRECT stays off because HF Spaces
terminates TLS upstream.
- urls.py: add a non-API catch-all view that serves dist/index.html
so Vue Router (and its Lara Croft 404) handles client-side routes.
- requirements.txt: drop gdown, add huggingf…
fix(coins): redesign query graph for legibility and floating dropdowns
Andrej Janchevski
9daa9d0
The query-graph editor had several long-standing issues: long entity /
relation names clipped pill content, edge labels overflowed into adjacent
cells, dropdown menus were trapped inside the FitText overflow:hidden,
edge arrows disappeared on first paint, and wide structures (3p/ip/pi)
crammed against the wrap edges with no escape valve.
- New common/FitText.vue is a fixed-size container that auto-shrinks its
inner font-size to fit width + height, falling back to wrap with
overflow-wrap: anywhere when content is too long even at the floor
scale.
- QueryGraph promotes FitText to be the visible cell/edge-label chrome
so edge endpoints land on a stable rectangle regardless of content
length. SVG renders only after the first measurement, with a heavier
CSS-blurred halo path replacing the bbox-clipped SVG glow filter so
horizontal edges look identical to diagonal ones. Source-side
endpoint dots stay; target-side dots dropped because they covered
arrowheads. Cells gain cor…
feat(frontend): wire kganomaly and multiproxan demos into nav and home
Andrej Janchevski
4f5b792
- Router gains the two new /demos routes.
- NavBar adds them to the Demos dropdown.
- HomeView lists the two new demos alongside the COINs one.
feat(multiproxan): add graph-generation demo UI
Andrej Janchevski
d014501
New /demos/multiproxan route covers thesis § 4.3:
- ParametersPanel exposes dataset, sampling mode, and per-mode controls.
- The store posts to /graph-gen/generate (and /continue), consumes the
SSE stream via the shared composable, and tracks live phase / step /
ETA / frame preview state for the view.
- The view stitches the parameters, the SseProgressBar, the StepTimeline,
and the PreviewReel into a single page; "Continue" extends the chain
past the initial denoise to surface MultiProxAn's iterative refinement.
feat(kganomaly): add diffusion-based KG denoising demo UI
Andrej Janchevski
9d1139a
New /demos/kganomaly route walks the user through the thesis § 4.4 pipeline:
- Pick a dataset and a sample subgraph (SampleSubgraphCard renders the
current entity/edge state with type-coloured nodes).
- Optionally inject random edge noise; run the standard or multiprox
reverse-diffusion correction; the live section streams the per-step
progress + frame previews via the shared SseProgressBar / PreviewReel.
- ChangeList contrasts the noised vs corrected graph at the edge level
(added / removed / kept).
The store wires the SSE composable to the backend's progress events,
maintains the step-duration + KG log-likelihood sparkline buffers, and
exposes start / continue / cancel actions to the view.
feat(frontend): add shared SSE and progress-display components
Andrej Janchevski
2e2cad3
Pieces shared by the kg-anomaly and multiproxan demos:
- useSseStream composable parses event-stream frames into typed
callbacks (onProgress / onPreview / onResult / onError) with abort
+ reconnect handling.
- SseProgressBar renders the running phase, step/total, elapsed-vs-ETA,
and a step-duration sparkline; takes an optional metric series so
callers can stack a second sparkline (e.g. KG log-likelihood) under it.
- StepTimeline shows the per-phase timeline of a multi-stage run.
- PreviewReel shows base64 frames as a small reel with playhead scrubbing.
- InferenceErrorBanner is the shared error/abort banner.
- EtaTracker is the rolling-window utility that powers ETA + sparkline
data on the stores.
feat(multiproxan): stream graph-generation progress and refine comm20 render
Andrej Janchevski
713aa17
- GraphGenGenerateView and GraphGenContinueView now declare the
EventStreamRenderer alongside JSONRenderer so the SSE branch is
served when the client requests text/event-stream.
- _render_comm20 mirrors MultiProxAn's visualize_non_molecule:
largest connected component + spring layout + normalized-Laplacian
eigenvector colouring on a green palette, no labels, grey edges.
Uses pure PIL + networkx + torch.linalg.eigh to dodge the
matplotlib/numpy MKL DLL conflict on Windows request threads.
feat(kganomaly): add streaming denoising backend with KG-likelihood metric
Andrej Janchevski
bc4fc5c
- New endpoints emit Server-Sent Events via api/renderers.py so the
diffusion reverse process streams progress + frame previews instead of
blocking on a single response.
- kg_likelihood.py exposes a per-step mean log-sigmoid score from the
frozen KG embedder + link ranker; kg_anomaly_inference.py logs it on
frame boundaries and attaches kg_log_likelihood / kg_log_likelihood_step
to progress events so the UI can render a "denoising-is-working"
trace alongside step-duration sparklines.
- registry._build_sample_subgraphs now accepts a seed (so each request
gets a different DFS partition), shuffles candidate (row, col) pairs,
and rejects ill-shaped bipartite samples whose halves can't form valid
inpaint quadrants. Sampler.get_context_subgraph_samples_dfs gains the
matching seed parameter in the research code.
- api.yaml + backend README document the new optional progress fields.
feat(coins): add sample-query endpoint and resolve Freebase MIDs to names
Andrej Janchevski
db54566
Add GET /coins/datasets/{id}/sample-query that produces structurally
valid KG queries for all 7 query structures by delegating to
Query.instantiate() from the research code rather than hand-rolling
graph walks. Returns anchors, variables, relations, and a known target
entity — guaranteed to form a real path/intersection in the training KG.
Also resolve Freebase MID identifiers (e.g. /m/06rf7) to human-readable
names (e.g. Schleswig Holstein) using the ent2name.txt lookup table:
- Entity and relation search endpoints now return a `label` field with
cleaned display names alongside the raw `name`
- Search filtering matches against both raw names and cleaned labels,
so searching "Chicago" finds /m/01yjl (Chicago Cubs)
- sample-query and sample-triples responses carry resolved labels
fix(coins): rebuild machines array when cached .npz has wrong length
Andrej Janchevski
b609540
Stale machines_*.npz files on disk can have a different length than the
current Leiden partition's num_communities, causing an IndexError during
COINs experiment preparation. Rebuild machines = zeros(num_communities+2)
in both _load_all_loaders and the cached-loader path in
_load_coins_experiment to match the website's single-device setup.
feat(coins): add interactive query builder and reasoning dashboard
Andrej Janchevski
cd5136e
Full COINs demo at /demos/coins with query structure picker (7 templates),
searchable entity/relation dropdowns with server-side pagination, algorithm
selector filtered by structure+dataset compatibility, SVG query graph
visualization with slot-based editing, and a results dashboard showing
ranked predictions, community rank callout, and timing breakdown with
speedup estimate.
- Pinia store manages the full query lifecycle (registry load, slot
filling, predict call, error handling for 429/422/503)
- QueryGraph uses CSS Grid with ResizeObserver-driven edge routing
- SearchablePicker debounces 250ms with AbortController cancellation
- Route /demos/coins lazy-loaded, nav link + DemoPreviewCard wired
feat(404): randomise between core design and jolie lara croft stills
Andrej Janchevski
6cc7c3d
- NotFoundView now picks one of two on-theme Lara Croft images per
visit: the classic TR1 render by Core Design (jungle palette, fits
the site's green theme) and the 2001 film promotional still of
Angelina Jolie in full Lara costume
- Each variant carries its own attribution line: CC BY-NC-SA 4.0
credit for the Core Design render via Raiding The Globe, and an
honest non-commercial fan-site disclosure for the Paramount film
still via the Guardian
- Responsive layout: image + copy side-by-side on desktop, stacks
and centres below 640px
feat(frontend): bootstrap vue+semantic site with homepage and cv page
Andrej Janchevski
8bf4795
Initial Vite + Vue 3 + Pinia + Vue Router + Fomantic UI scaffold under
src/frontend/, implementing the first two pages of the site per the
frontend bootstrap plan:
- App shell: NavBar with theme toggle, persistent GraphBackground
(SVG rAF animation driven by shallowRef + triggerRef, sampling
from data/motifs.json — 13 three-node + 199 four-node directed
motifs exported from the COINs research code), routed views
- Dark mode via data-theme attribute + CSS custom properties in
styles/tokens.css; persisted in localStorage, defaults to system
preference, surfaced through Pinia theme store
- Homepage (/): hero intro with avatar, research demo teaser cards,
NELL Fact of the Day (seeded by today's ISO date so it only
changes once a day, no reload button), System Status card
aggregating /health, /, /methods in parallel, recent work and
education highlights. Sections are non-collapsible on the homepage
- CV page (/cv): full mirror of docs/Profile.pdf transcribed into
data/c…
feat(coins): add optional seed param and label fields to sample-triples
Andrej Janchevski
ee3e8fe
- registry.sample_triples now accepts seed= for deterministic sampling
via random.Random(seed); omitted seed preserves prior random behaviour
- Each head/relation/tail gains a dataset-cleaned label alongside id and
name (NELL strips concept:, Freebase strips /m/, WordNet drops POS
suffix) so the frontend can show display-friendly strings without
duplicating the cleanup logic
- OpenAPI, Postman collection, and backend README updated in lockstep
- Enables a day-stable NELL Fact of the Day widget seeded by ISO date
fix(research): drop remaining wandb calls and qualify kg imports
Andrej Janchevski
95c7d01
Continues the wandb-removal pass so the research modules can be loaded
from the Django backend without the optional dependency. Also switches
diffusion_model_discrete_kg.py to fully qualified imports
(graph_generation.src.diffusion.*, graph_generation.src.metrics.*) to
avoid name collisions with MultiProxAn's own metrics package, which is
also on sys.path at runtime.
feat(kg-anomaly): add correct/continue endpoints with SSE streaming
Andrej Janchevski
aaf56bb
Implements the two remaining inference endpoints for the KG anomaly
feature, following the MultiProxAn graph-generation pattern:
- POST /kg-anomaly/correct: standard denoising (correct/generate tasks)
or MultiProx Gibbs init; returns SSE stream with progress, preview,
and terminal result events (before/after images, chain GIF, diff).
- POST /kg-anomaly/continue: advances a MultiProx session one step.
- Adds kg_anomaly_inference.py with tensor building, change detection,
directed subgraph rendering (PIL + networkx), and an apply_edge_noise
helper that task-aware forward-diffuses edges for demo input.
- Extends GET /kg-anomaly/datasets/{id}/sample-subgraphs with
noise_level/task/seed query params so callers can fetch pre-noised
subgraphs ready for correction.
- Registry: adds DiscreteDenoisingDiffusionKG loader that reconstructs
dataset_infos from checkpoint state_dict shapes + COINs experiment.
- Adds graph_generation/src to sys.path for bare imports inside the
research…
docs(postman): add thesis-optimal multiprox params and force-unlock endpoint
Andrej Janchevski
c50d15c
- QM9 multiprox: t=0.5, t'=0.004 (Table 4.3.1 best valid config)
- Comm20 multiprox: t=0.4, t'=0.1 (Table C.2.1 best orbit/degree)
- Add POST /debug/force-unlock request to Health folder
- Auto-chaining test scripts for multiprox state between init/continue
- Update README with SSE protocol and new endpoints
- Update backend_multiproxan plan to reflect current design decisions
fix(coins): create tensors on model device instead of CPU
Andrej Janchevski
c1b3cc7
Tensor construction in coins_predict_inner used default CPU device,
causing device mismatch errors when the embedder is on CUDA. Now
reads device from embedder parameters and passes it to all pt.tensor,
pt.full, and pt.arange calls.
feat(graphgen): implement generate and continue endpoints with SSE streaming
Andrej Janchevski
c6841f4
- New graphgen_inference.py: denoising loops, Gibbs ensemble, state
blob serialization, PIL+networkx rendering (no matplotlib — its GUI
backend crashes in Django threads on Windows)
- Safe checkpoint loading via _safe_load_lightning_checkpoint: bypasses
load_from_checkpoint to avoid DDP pickle, deepcopy, and CUDA OOM
crashes on comm20 checkpoints trained with DistributedDataParallel
- SSE streaming protocol with three event types (progress, preview,
result) for real-time Postman visualization
- Inference lock with owner tracking and debug force-release endpoint
- .long() fix on discrete model outputs to prevent float index errors
fix(research): remove wandb dependency and guard optional imports
Andrej Janchevski
16cab72
- Strip wandb imports and calls from MultiProxAn diffusion models and
utils (prevents ImportError at checkpoint load time)
- Wrap graph_tool, pyemd, pygsp, dist_helper imports in try/except
across spectre_utils, molecular_metrics, train_metrics (these are
only needed for training metrics, not inference)
- Fix pandas deprecation in COINs load_graph.py (iteritems -> items,
to_frame column naming)
Implement COINs predict endpoint
Andrej Janchevski
3ad32ba
Fixes
Andrej Janchevski
df10af3
Implement backend discovery endpoints
Andrej Janchevski
4f1e196
Implement API skeleton
Andrej Janchevski
0b4eacc
Handle checkpoints
Andrej Janchevski
7f78dbf
Initial commit - add source files from research repos