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.
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.
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…
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 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
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…
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