Skip to content

Add cosine-similarity LOINC candidate retrieval - #1775

Open
dmondal06 wants to merge 1 commit into
sunlabuiuc:masterfrom
dmondal06:loinc-candidate-retrieval
Open

dmondal06 wants to merge 1 commit into
sunlabuiuc:masterfrom
dmondal06:loinc-candidate-retrieval

Conversation

@dmondal06

Copy link
Copy Markdown

Title
Add cosine-similarity LOINC candidate retrieval

Contributor
Deepa Mondal (GT username dmondal31, dmondal31@gatech.edu)

Contribution type
Model

Paper
Tu et al. (2022), Automated LOINC Standardization Using Pre-trained Large Language Models
https://proceedings.mlr.press/v193/tu22a.html

Description
This PyHealth model implements the cosine retrieval step in Section 3.6. It
accepts embeddings of local lab names and a shared target catalog, then returns
ranked catalog indices. It is encoder-agnostic. The example uses TF-IDF to
exercise the ranking method with synthetic records. The implementation covers
the inference stage. The published experiment also uses Sentence-T5,
contrastive fine-tuning and MIMIC-III mappings.

File guide

  • pyhealth/models/loinc_retriever.py — shared-catalog cosine retrieval.
  • tests/core/test_loinc_retriever.py — deterministic shape, ranking, tie,
    validation and gradient tests.
  • examples/synthetic_loinc_mapping_cosine.py — runnable specimen ablation
    using word and character TF-IDF on the same queries and catalog.
  • docs/api/models/pyhealth.models.loinc_retriever.rst — API documentation.

Verification
python -m pytest -q tests/core/test_loinc_retriever.py
python -m examples.synthetic_loinc_mapping_cosine

On the synthetic fixture, adding specimen improved top-1 from 9/16 to
16/16 with word unigrams and from 7/16 to 16/16 with character n-grams.
All four settings reached 16/16 at top-3 and top-5. The hand-authored
fixture tests specimen ambiguity under controlled conditions.

@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown

Test Coverage

Total: 88.77% (61481 / 69257 lines)

Modified file Coverage Lines
pyhealth/models/__init__.py 100.00% 132 / 132
pyhealth/models/loinc_retriever.py 97.83% 45 / 46

Workflow run · 55c3d0b

@solarsys solarsys added the status: automatic The PR will go through automatic review process. label Dec 1, 2026
@solarsys

solarsys commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit 55c3d0b

scaled = embeddings / embeddings.abs().amax(dim=-1, keepdim=True)
return F.normalize(scaled, dim=-1)

def forward(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[high] forward rejects the Trainer's batch keys (patient_id)

forward(self, source_embedding, label=None) has no **kwargs. PyHealth's Trainer calls self.model(**data) with the full dataloader batch (trainer.py:324, and evaluation reads data["patient_id"] at trainer.py:433), so any dataset-backed train or eval call raises TypeError: unexpected keyword argument 'patient_id'. The model is also documented as accepting dataset= and returns loss/y_true/y_prob, which is the Trainer contract. Fix: match BaseModel.forward's convention and accept **kwargs (ignoring extra keys), and add a test that runs the model through create_sample_dataset + get_dataloader and a batch that includes patient_id.

raise ValueError(f"{name} must be a nonempty matrix.")
if not embeddings.is_floating_point() or not torch.isfinite(embeddings).all():
raise ValueError(f"{name} must contain finite floating-point values.")
if (embeddings == 0).all(dim=-1).any():

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[medium] Zero query rows from TF-IDF fail the whole batch

The check (embeddings == 0).all(dim=-1).any() rejects any zero source row, and the entire batch then raises. A TF-IDF encoder, which the example and the description use, produces a zero row for any lab name with no catalog vocabulary, a common case in real local lab names. One unseen name therefore fails a whole batch. Fix: either give zero-norm source rows a zero score (for example by clamping the norm) and document that, or document that callers must filter such rows. Add a test for a zero source row either way.

fields = "name + specimen" if include_specimen else "name only"
print(f"{analyzer:7s} | {fields:15s} | " + " | ".join(metrics))
if analyzer == "word":
print(f" Glucose quantitative -> {CATALOG[ranking[0, 0].item()]}")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] Demo print is inside the setting loop and unlabeled

The line print(f" Glucose quantitative -> ...") runs for both the name-only and name+specimen settings, so the same line appears twice without saying which format produced it. Move it out of the inner loop or add fields to the output so the reader can tell the two results apart.

.. autoclass:: pyhealth.models.loinc_retriever.LOINCRetriever
:members:

The model reproduces the cosine retrieval step in

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] Page says the model reproduces the paper's step without noting the omitted parts

"The model reproduces the cosine retrieval step in Tu et al. (2022)" reads as a full reproduction. The description says the paper's Sentence-T5 encoder, contrastive fine-tuning and MIMIC-III mappings are not included. Add one sentence saying which parts are left out.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI Review

suggestion: need change
decision: need change

Thank you, Deepa, for this contribution. LOINCRetriever is an encoder-agnostic cosine retrieval model for LOINC candidates, and it comes with a synthetic TF-IDF example, unit tests and an API page. Coverage is above the bar: loinc_retriever.py is at 97.83% and the whole repository is at 88.77%. The change is close, but two problems need fixing first.

To get this merged:

  1. forward can't take a full dataset batch. LOINCRetriever.forward(self, source_embedding, label=None) has no **kwargs. PyHealth's Trainer calls model(**batch), and dataset batches also carry fields such as patient_id. So training or evaluation through the Trainer or a dataloader would most likely raise a TypeError. Your example avoids this by passing source_embedding explicitly. Please accept **kwargs and ignore the extra fields, as other PyHealth models do. Please also add a test that runs a dataset batch through model(**batch). If you only intend direct tensor calls, drop the dataset argument and say so in the docs.
  2. A zero query vector fails the whole batch. _validate_embeddings rejects any all-zero row, and this check also runs on the query side. A local lab name with no terms in the TF-IDF vocabulary gives a zero row. That is a realistic case for an encoder-agnostic model, and it would make the entire batch fail. Please either handle zero queries gracefully (for example, give them a score of 0 for every candidate) or state the limitation clearly in the docstring and API docs. Please also add a test for whichever you choose.

Optional suggestions:

  • In the example, the "Glucose quantitative -> ..." line prints for both query formats without saying which is which. Labelling it would help.
  • The API page says the model "reproduces" the paper's retrieval step. Since the Sentence-T5 encoder and the fine-tuning aren't included, "implements the cosine ranking step" would be more precise.

Reviewed commit 55c3d0b

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: automatic The PR will go through automatic review process.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants