Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ internal versions are summarized under 0.3.33.
## [Unreleased]

### Fixed
- Corpus manifests accept dotted shard names without a tar extension. The CLI reports entries it cannot resolve. (#19)
- Archive scans release processed headers. Parallel parsing keeps a bounded window and continues in order after empty articles. Compressed archives can contain rootless XML members without stopping the build. (#12, #24)
- IVF-PQ training saves a flat chunk index when the corpus has no training text. Builds also recognize untrained indexes created by `--init-indices-only` and persist the training result before updating its marker. (#11)
- `query_terms()`, `find_rare_terms()`, and Stage-2 lexical front-loading now retain 3–4 character all-uppercase acronyms (such as `HIV`, `EGFR`, and `ALL`, plus plurals like `TLRs`) with word-boundary matching that still accepts plural, numbered, and inhibitor forms (`RNAs`, `TLR4`, `ACEi`), prioritize digit/hyphen and long-term matches ahead of acronyms, and normalize SQLite-compatible dashes and subscripts before tokenizing. All-caps prose such as `WHAT IS THE ROLE OF RNA` does not turn ordinary words into acronyms, while all-caps keyword queries such as `EGFR NSCLC` keep theirs. (#9)

## [0.3.36] - 2026-11-30
Expand Down
15 changes: 6 additions & 9 deletions src/litkit/build/indices.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
faiss_load,
unwrap_core_and_kind,
kind_and_core,
extract_ivf,
)
from litkit.build.helpers import ensure_parent
from litkit.progress import eprint as _eprint
Expand Down Expand Up @@ -238,7 +237,7 @@ def load_or_create_chunk_index(

if chunk_index_path.exists():
chunk_index = faiss_load(chunk_index_path)
_, core = kind_and_core(chunk_index)
kind, core = kind_and_core(chunk_index)
mt = getattr(core, "metric_type", faiss.METRIC_INNER_PRODUCT)

if mt != faiss.METRIC_INNER_PRODUCT:
Expand All @@ -254,24 +253,22 @@ def load_or_create_chunk_index(
faiss_save(chunk_index, chunk_index_path)

# Check if IVF-PQ needs training
ivf = extract_ivf(chunk_index)
if isinstance(ivf, faiss.IndexIVFPQ) and not getattr(ivf, "is_trained", False):
# FAISS can expose the inner IVFPQ as its IndexIVF base class.
if kind == "ivf" and not core.is_trained:
_eprint(
"[train] WARNING: chunks index is IVFPQ but untrained; "
"ignoring stale trained flag and retraining."
)
_clear_trained_flag(chunk_trained_flag)
needs_training = True
else:
if chunks_index == "flat":
base = flat_ip_index(chunk_dim)
chunk_index = faiss.IndexIDMap2(base)
_clear_trained_flag(chunk_trained_flag)
ensure_parent(chunk_index_path)

if is_faiss_writer:
with FileLock(db_lock_path), FileLock(faiss_lock_path):
faiss_save(chunk_index, chunk_index_path)
ensure_parent(chunk_index_path)
faiss_save_force(chunk_index, chunk_index_path)
_clear_trained_flag(chunk_trained_flag)
else:
raise RuntimeError(
"CHUNK index does not exist. Start a writer with --faiss-writer "
Expand Down
93 changes: 40 additions & 53 deletions src/litkit/build/training.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
flat_ip_index,
ivfpq_index,
safe_pq_m,
faiss_save,
faiss_save_force,
auto_set_nprobe,
PQ_BITS,
)
Expand Down Expand Up @@ -245,26 +245,28 @@ def _flush_train(buf: list[str]) -> np.ndarray:
texts_buf.clear()

samples_prog.finish()

# Handle no training data case

def flat_fallback() -> faiss.Index:
index = faiss.IndexIDMap2(flat_ip_index(chunk_dim))
if is_faiss_writer:
with FileLock(db_lock_path), FileLock(faiss_lock_path):
ensure_parent(chunk_index_path)
faiss_save_force(index, chunk_index_path)
_clear_trained_flag(chunk_trained_flag)
return index

if not X_train_list:
_eprint("[train] WARNING: no chunk texts found for training; falling back to FLAT index")
base = flat_ip_index(chunk_dim)
chunk_index = faiss.IndexIDMap2(base)
_clear_trained_flag(chunk_trained_flag)
if is_faiss_writer:
faiss_save(chunk_index, chunk_index_path)
return chunk_index

return flat_fallback()

# Prepare training data
X_train = np.vstack(X_train_list)
if X_train.shape[0] > train_samples:
X_train = X_train[:train_samples]

n_train = int(X_train.shape[0])
_eprint(f"[train] chunk training samples: target={train_samples} collected={n_train}")
ensure_parent(chunk_index_path)


# Training decision tree
pq_bits = PQ_BITS
k = 1 << pq_bits
Expand All @@ -275,14 +277,8 @@ def _flush_train(buf: list[str]) -> np.ndarray:
# Check if we have enough data for IVF-PQ
if n_train < max(min_for_micro, min_for_pq, 100 * m_candidate):
_eprint(f"[train] not enough samples for IVF-PQ (n={n_train}); using FLAT IP")
base = flat_ip_index(chunk_dim)
chunk_index = faiss.IndexIDMap2(base)
if is_faiss_writer:
with FileLock(db_lock_path), FileLock(faiss_lock_path):
faiss_save(chunk_index, chunk_index_path)
_clear_trained_flag(chunk_trained_flag)
return chunk_index

return flat_fallback()

# Choose nlist with data-aware caps
eff_nlist = _effective_nlist(n_train, ivf_nlist, user_forced=ivf_nlist_forced)
max_by_samples = max(1, n_train // 40)
Expand All @@ -293,14 +289,8 @@ def _flush_train(buf: list[str]) -> np.ndarray:
# Re-check adequacy with final nlist
if eff_nlist < 8 or n_train < max(min_for_pq, 50 * eff_nlist, 100 * m_candidate):
_eprint(f"[train] nlist/m under-sampled (n={n_train}, nlist={eff_nlist}, m={m_candidate}); using FLAT IP")
base = flat_ip_index(chunk_dim)
chunk_index = faiss.IndexIDMap2(base)
if is_faiss_writer:
with FileLock(db_lock_path), FileLock(faiss_lock_path):
faiss_save(chunk_index, chunk_index_path)
_clear_trained_flag(chunk_trained_flag)
return chunk_index

return flat_fallback()

# Train IVF-PQ
m = m_candidate
if m != pq_m:
Expand Down Expand Up @@ -337,32 +327,29 @@ def _flush_train(buf: list[str]) -> np.ndarray:
# Set nprobe
auto_set_nprobe(new_chunk_index, nprobe)
chunk_index = faiss.IndexIDMap2(new_chunk_index)

# Save and write trained flag
if is_faiss_writer:
with FileLock(db_lock_path), FileLock(faiss_lock_path):
faiss_save(chunk_index, chunk_index_path)

_tf_tmp = chunk_trained_flag.with_suffix(".tmp")
with open(_tf_tmp, "w") as fh:
fh.write(json.dumps({

except Exception as e:
_eprint(f"[train] WARNING: IVF-PQ training failed ({e}); falling back to FLAT")
return flat_fallback()

if is_faiss_writer:
with FileLock(db_lock_path), FileLock(faiss_lock_path):
ensure_parent(chunk_index_path)
faiss_save_force(chunk_index, chunk_index_path)
flag_tmp = chunk_trained_flag.with_suffix(".tmp")
with open(flag_tmp, "w") as fh:
json.dump(
{
"trained_on": int(time.time()),
"n": n_train,
"nlist": eff_nlist,
"m": m,
}, indent=2))
fh.flush()
os.fsync(fh.fileno())
os.replace(_tf_tmp, chunk_trained_flag)
maybe_fsync_dir(chunk_trained_flag)

return chunk_index

except Exception as e:
_eprint(f"[train] WARNING: IVF-PQ training failed ({e}); falling back to FLAT")
chunk_index = faiss.IndexIDMap2(flat_ip_index(chunk_dim))
if is_faiss_writer:
with FileLock(db_lock_path), FileLock(faiss_lock_path):
faiss_save(chunk_index, chunk_index_path)
_clear_trained_flag(chunk_trained_flag)
return chunk_index
},
fh,
indent=2,
)
fh.flush()
os.fsync(fh.fileno())
os.replace(flag_tmp, chunk_trained_flag)
maybe_fsync_dir(chunk_trained_flag)
return chunk_index
5 changes: 2 additions & 3 deletions src/litkit/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ def _version_banner() -> str:
# Only imports needed BEFORE argparse runs (for --help/--version) are at module level.
# Other stdlib imports are deferred to their use sites to minimize import-time side effects.
import argparse
import logging
import threading
from pathlib import Path
from typing import Any, Iterator
Expand Down Expand Up @@ -270,9 +271,6 @@ def _load_heavy_deps() -> None:



# logging.basicConfig(level=logging.WARNING, format="%(levelname)s %(name)s: %(message)s")


def deps() -> SimpleNamespace:
"""Load heavy dependencies (idempotent) and return the deps namespace.

Expand Down Expand Up @@ -1598,6 +1596,7 @@ def get_chunks(conn, ids: list[int]) -> list[dict[str, Any]]:
# -------------------- Main --------------------
def main():
"""CLI entry point."""
logging.basicConfig(format="%(levelname)s %(name)s: %(message)s")
# Windows pipes default to the ANSI code page, which can lose scientific text.
if (
os.name == "nt"
Expand Down
Loading
Loading