Skip to content

fix(medcat): Keep context vectors of concepts trained in only one CDB in merge_cdb - #679

Merged
mart-r merged 1 commit into
CogStack:mainfrom
chenyangsu:fix/merge-cdb-context-vectors
Nov 26, 2026
Merged

mart-r merged 1 commit into
CogStack:mainfrom
chenyangsu:fix/merge-cdb-context-vectors

Conversation

@chenyangsu

Copy link
Copy Markdown
Contributor

When a CUI is in both CDBs but only one of them has context vectors for it, merge_cdb keeps the trained count_train but not the vectors:

cdb1.cui2info["C1"] = get_new_cui_info(
    cui="C1", preferred_name="Kidney failure", names={"kidney~failure"},
    count_train=0, context_vectors=None)
cdb2.cui2info["C1"] = get_new_cui_info(
    cui="C1", preferred_name="Kidney failure", names={"kidney~failure"},
    count_train=12, context_vectors={"long": np.ones(300)})
merged = merge_cdb(cdb1, cdb2)            # same for overwrite_training=1 or 2
merged.cui2info["C1"]["count_train"]      # 12
merged.cui2info["C1"]["context_vectors"]  # None

In the reverse case (cdb1 trained, cdb2 not) with overwrite_training=2, the vectors come out as zeros, because the weighted average uses [0.0, 1.0] against np.zeros(300).

With this change, a concept trained in only one CDB keeps that CDB's vectors; when both have vectors the merge is unchanged. This follows what the count_train merge already does in the same cases. If you would rather keep cdb1 strictly first for overwrite_training=1 even when cdb1 has no vectors, I can change that.

Testing: the new test_merge_cdb_keeps_vectors_trained_in_one_cdb covers both directions for each overwrite_training value; 4 of its 6 subtests fail on main. python -m unittest tests.utils.test_cdb_utils: 16 tests OK. ruff check medcat --preview and mypy pass.

…erge_cdb

When a concept is in both CDBs but only one has context vectors,
merge_cdb dropped cdb2's vectors (cdb1 untrained, any overwrite mode)
or replaced cdb1's vectors with zeros (cdb2 untrained,
overwrite_training=2), while count_train kept the trained count.
Copy the trained CDB's vectors in both cases.

@mart-r mart-r left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the contribution and the thorough description!

Good catch! And good PR!

Thanks.

PS: We haven't used CDB merge in production too much so we haven't been able to catch this. Thanks again!

@mart-r
mart-r merged commit 83c41c7 into CogStack:main Nov 26, 2026
18 of 19 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants