Skip to content
Merged
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ internal versions are summarized under 0.3.33.
## [Unreleased]

### Added
- `litkit export-vectors` writes FAISS indexes, text hashes, source checksums, model revisions and per-paper attribution. Use `--license` to select licenses. (#65)
- Paper and passage results report publication type and retraction status. Search with repeatable `--type` and `--exclude-type` filters. (#58)
- `litkit build-fts` indexes passage text for exact search. The optional index stays current through updates, rebuilds and shard merges. (#56)

Expand Down
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,3 +227,31 @@ derivative works, distribute copies to the public, perform publicly and display
others to do so.

LANL software release O5068.

## Vector releases

`litkit export-vectors RELEASE --workspace WORKSPACE` writes the FAISS files,
a SQLite mapping from vector IDs to documents and hashed passages, source
checksums and build settings in `manifest.json`, and paper citations and
licenses in `attribution.jsonl`. The release omits abstracts and passage text.
Pass `--license CC-BY-4.0` to include papers with that license. Repeat the
option for more licenses. Articles without a license have the label `unknown`.

New builds record each archive's SHA-256, chunk and table settings, LitKit
version and model snapshot revisions. For a legacy workspace, supply a JSON
file with `--settings` and make its source archives available. The file uses
the fields below. Substitute the actual model revisions and build options.

```json
{"litkit_version":"0.4.0","chunk_target_chars":1200,"chunk_min_chars":300,
"chunk_overlap":200,"include_tables":false,"max_table_chars":4000,
"paper_model":{"name":"allenai/specter2_base","revision":"PAPER_COMMIT"},
"chunk_model":{"name":"sentence-transformers/all-mpnet-base-v2","revision":"CHUNK_COMMIT"}}
```

If archives used different settings, put shared fields in a `defaults` object
and archive-specific fields in a `sources` object keyed by relative archive
name. For example, `{"sources":{"old.tar":{"chunk_overlap":100}}}` fills that
archive's missing overlap setting. Supply all unrecorded fields for legacy
archives. Recorded settings must agree with the values supplied for that archive.
Use `--source-root DIR` when the legacy archives have moved.
17 changes: 17 additions & 0 deletions src/litkit/build/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,23 @@ def pack_body(meta: ArticleMeta, max_chars: int, min_chars: int, overlap_chars:
return chunks


def paper_input(meta):
title = (meta.get("title") or "").strip()
abstract = (meta.get("abstract") or "").strip()
return (title + " " + abstract).strip() or (
meta["paragraphs"][0][:800] if meta["paragraphs"] else "untitled"
)


def article_passages(meta, paper_text, target, minimum, overlap):
"""Yield the stable ordinal, text, page, section and citations for each vector."""
abstract_refs = tuple(dict.fromkeys(rid for _, _, rid in meta.get("abstract_citations", [])))
if paper_text:
yield -1, paper_text, None, "Abstract" if (meta.get("abstract") or "").strip() else None, abstract_refs
for ordinal, chunk in enumerate(pack_body(meta, target, minimum, overlap)):
yield ordinal, chunk[0], chunk[1], getattr(chunk, "section", None), getattr(chunk, "citations", ())


def dedupe_papers_with_doc_ids(
ids: list[int], texts: list[str], doc_ids: list[str], *, keep_last: bool = False
) -> tuple[list[int], list[str], list[str]]:
Expand Down
53 changes: 33 additions & 20 deletions src/litkit/build/ingest_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import faiss

from litkit.progress import eprint as _eprint
from litkit.portable.record import SOURCE_SCHEMA, archive_identity, source_record, settings_record
from litkit.embeddings.base import (
progress_newline as _progress_newline,
progress_write as _progress_write,
Expand Down Expand Up @@ -60,7 +61,8 @@
from litkit.db.sharding import producer_shard_lock
from litkit.segments.metadata import verify_legacy_shard
from litkit.build.helpers import (
pack_body,
article_passages,
paper_input,
dedupe_papers_with_doc_ids,
dedupe_chunks_with_doc_ids,
)
Expand Down Expand Up @@ -508,12 +510,24 @@ def stage_indexes(paper_dir, chunk_dir):
revised_shard_papers.clear()

def process_tar(tpath: Path) -> None:
provenance = None
try:
initial_identity = archive_identity(tpath)
except FileNotFoundError:
initial_identity = None
source_settings = settings_record(chunk_target_chars, chunk_min_chars, chunk_overlap, include_tables,
max_table_chars, paper_embedder, chunk_embedder)
rebuilding_tar = str(tpath) in rebuild_tars
# Number of *persisted* members previously processed for this tar shard
start_persisted = int(ckpt_stream.get(str(tpath), 0))
processed_count = start_persisted # increments after each successfully handled member
persisted_count = start_persisted # last value safely fsynced via commit + checkpoint

def flush_tar_batch(members):
if initial_identity is not None and archive_identity(tpath) != initial_identity:
raise ValueError(f"Source changed while ingesting {tpath}")
flush_batch(str(tpath), members)

# Set LITKIT_TAR_PRESCAN=0 to skip counting members
total_members = (
count_tar_xml_members(tpath)
Expand Down Expand Up @@ -604,7 +618,7 @@ def _render(force: bool = False):
if manifest_article is not None and meta is not None:
refresh_known_member(f, m, meta, manifest_article)
if pending_refreshes >= ckpt_every:
flush_batch(str(tpath), start_persisted)
flush_tar_batch(start_persisted)
skipped += 1
if skipped == start_persisted:
_render(force=True) # render resume point
Expand All @@ -631,7 +645,7 @@ def _render(force: bool = False):
if manifest_article is not None and meta is not None:
refresh_known_member(f, m, meta, manifest_article)
if pending_refreshes >= ckpt_every:
flush_batch(str(tpath), processed_count + 1)
flush_tar_batch(processed_count + 1)
processed_count += 1
continue

Expand All @@ -644,6 +658,12 @@ def _render(force: bool = False):
# SLOW PATH - Savepoint-protected writes
# ═══════════════════════════════════════════════════════════════════

if provenance is None:
if initial_identity is None:
raise ValueError(f"Source appeared after ingestion began: {tpath}")
provenance = source_record(tpath, source_settings, expected=initial_identity)
conn.execute(SOURCE_SCHEMA)

# Snapshot buffer lengths BEFORE processing so we can truncate on rollback
buf_snapshot = (
len(paper_ids_buf),
Expand Down Expand Up @@ -727,11 +747,7 @@ def _render(force: bool = False):
)
pid = cur.lastrowid

ta = (meta["title"] or "").strip()
ab = (meta["abstract"] or "").strip()
ta_ab = (ta + " " + ab).strip() or (
meta["paragraphs"][0][:800] if meta["paragraphs"] else "untitled"
)
ta_ab = paper_input(meta)
old_ids = []
reuse_embedding = False
if existing_row:
Expand Down Expand Up @@ -804,6 +820,10 @@ def _render(force: bool = False):
else:
cur.execute("UPDATE papers SET embedding_text=? WHERE id=?", (ta_ab, pid))

if provenance:
cur.execute("INSERT OR IGNORE INTO build_sources VALUES (?,?,?,?)", provenance)
cur.execute("UPDATE papers SET license=?,license_url=?,build_member=? WHERE id=?",
(meta.get("license"), meta.get("license_url"), f, pid))
bibliography = meta.get("references")
cur.execute("UPDATE papers SET references_json=?, publication_source=?, article_type=?, "
"publication_types=?, retracted=? WHERE id=?", (
Expand All @@ -812,16 +832,9 @@ def _render(force: bool = False):
))
if has_refresh_table:
cur.execute("DELETE FROM publication_refreshes WHERE path=?", (f,))
body = pack_body(meta, chunk_target_chars, chunk_min_chars, chunk_overlap)
abstract_section = "Abstract" if ab else None
abstract_refs = tuple(dict.fromkeys(rid for _, _, rid in meta.get("abstract_citations", [])))
proposed_chunks = [(-1, ta_ab, None, abstract_section, abstract_refs)] if ta_ab else []
proposed_chunks.extend(
(i, item[0], item[1], getattr(item, "section", None), getattr(item, "citations", ()))
for i, item in enumerate(body)
)

for ord_i, text_i, page, section, refs in proposed_chunks:
for ord_i, text_i, page, section, refs in article_passages(
meta, ta_ab, chunk_target_chars, chunk_min_chars, chunk_overlap
):
cur.execute(
"INSERT INTO chunks(paper_id, ord, text, page, section, cited_refs) VALUES (?,?,?,?,?,?)",
(pid, ord_i, text_i, page, section, json.dumps(refs) if refs else None),
Expand Down Expand Up @@ -894,12 +907,12 @@ def _render(force: bool = False):
or len(chunk_ids_buf) >= chunk_batch
or (not embed_producer and processed_count - persisted_count >= ckpt_every)
):
flush_batch(str(tpath), processed_count)
flush_tar_batch(processed_count)
persisted_count = processed_count
_render(force=True)

if pending_refreshes or processed_count != persisted_count or str(tpath) not in ckpt_stream:
flush_batch(str(tpath), processed_count)
flush_tar_batch(processed_count)
_render(force=True)
_progress_newline(sys.stderr)

Expand Down
2 changes: 1 addition & 1 deletion src/litkit/build/publication.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def reset_publication(conn: sqlite3.Connection, sqlite_dir: Path, seg_dir: Path)

if read_publication(conn):
conn.execute("UPDATE ingest_publication SET tar=NULL WHERE singleton=1")
for table in ("merged_paper_revisions", "obsolete_chunk_vectors", "obsolete_paper_vectors", "paper_doc_aliases", "paper_citation_links"):
for table in ("merged_paper_revisions", "obsolete_chunk_vectors", "obsolete_paper_vectors", "paper_doc_aliases", "paper_citation_links", "build_sources"):
if conn.execute("SELECT 1 FROM sqlite_master WHERE name=?", (table,)).fetchone():
conn.execute(f"DELETE FROM {table}")
if conn.execute("SELECT 1 FROM sqlite_master WHERE name='merged_shard_checkpoints'").fetchone():
Expand Down
6 changes: 6 additions & 0 deletions src/litkit/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1845,6 +1845,11 @@ def main():
sys.stderr.write("[env] Python >= 3.10 required.\n")
sys.exit(2)

if sys.argv[1:2] == ["export-vectors"]:
from litkit.portable.cli import main as portable_main
portable_main(sys.argv[1:])
return

if sys.argv[1:2] == ["build-fts"]:
from contextlib import closing
from litkit.config.paths import WorkspacePaths
Expand Down Expand Up @@ -1902,6 +1907,7 @@ def main():
ap = argparse.ArgumentParser(
description="An air-gapped HPC two-stage RAG pipeline for the PMC-OA corpus",
epilog=(
" litkit export-vectors DIR Export vectors and a text-free passage mapping\n"
" litkit build-fts [--workspace DIR] Index passage text for exact search\n"
"Progressive retrieval subcommands (all support --json, --limit, --max-chars):\n"
" litkit search-papers [query] Stage-1 / metadata search with filters\n"
Expand Down
5 changes: 4 additions & 1 deletion src/litkit/db/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
-- Paper vector input when multiple versions share an ID
embedding_text TEXT,
references_json TEXT,
license TEXT, license_url TEXT, build_member TEXT,
publication_source BLOB,
article_type TEXT,
publication_types TEXT,
Expand Down Expand Up @@ -94,7 +95,7 @@ def optional_paper_columns(
return {
name: (f"{prefix}{name}" if name in cols else "NULL")
for name in ("doc_id", "source_path", "doi", "year", "authors", "journal", "references_json",
"publication_source", "article_type", "publication_types", "retracted")
"license", "license_url", "build_member", "publication_source", "article_type", "publication_types", "retracted")
}


Expand Down Expand Up @@ -252,6 +253,8 @@ def ensure_paper_embedding_column(conn: sqlite3.Connection) -> None:


_ADDED_COLUMNS = (
("papers", "license", "TEXT"), ("papers", "license_url", "TEXT"),
("papers", "build_member", "TEXT"),
("papers", "publication_source", "BLOB"),
("papers", "article_type", "TEXT"),
("papers", "publication_types", "TEXT"),
Expand Down
11 changes: 10 additions & 1 deletion src/litkit/db/sharding.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ def _merge_revised_papers(conn, shard, mapping, since):
revisions = conn.execute(f"""
SELECT m.history_only, m.new_alias, p.doc_id, m.main_pid, p.id, dest.doc_id, p.pmid, p.pmcid, p.title, p.abstract,
{p_cols['source_path']}, {p_cols['doi']}, {p_cols['year']}, {p_cols['authors']}, {p_cols['journal']}, {p_cols['references_json']},
{p_cols['license']}, {p_cols['license_url']}, {p_cols['build_member']},
{p_cols['publication_source']}, {p_cols['article_type']}, {p_cols['publication_types']}, {p_cols['retracted']},
COALESCE(p.embedding_text, (SELECT c.text FROM {shard}.chunks c
WHERE c.paper_id=p.id AND c.ord=-1 ORDER BY c.id DESC LIMIT 1))
Expand All @@ -253,6 +254,7 @@ def _merge_revised_papers(conn, shard, mapping, since):
authors,
journal,
references_json,
license_name, license_url, build_member,
publication_source, article_type, publication_types, retracted,
embedding_text,
) in revisions:
Expand Down Expand Up @@ -284,6 +286,7 @@ def _merge_revised_papers(conn, shard, mapping, since):
(SELECT text FROM chunks WHERE paper_id=:id AND ord=-1 ORDER BY id DESC LIMIT 1)
) IS :input THEN in_index ELSE 0 END,
title=:title, abstract=:abstract, source_path=:source, embedding_text=:input, references_json=:refs,
license=:license, license_url=:url, build_member=:member,
publication_source=:publication_source, article_type=:article_type,
publication_types=:types, retracted=:retracted,
doi=COALESCE(NULLIF(:doi,''), doi),
Expand All @@ -292,6 +295,7 @@ def _merge_revised_papers(conn, shard, mapping, since):
journal=COALESCE(NULLIF(:journal,''), journal),
pmid=COALESCE(NULLIF(pmid,''), :pmid), pmcid=COALESCE(NULLIF(pmcid,''), :pmcid) WHERE id=:id
""", {"title": title, "abstract": abstract, "source": source_path, "input": embedding_text, "refs": references_json,
"license": license_name, "url": license_url, "member": build_member,
"publication_source": publication_source, "article_type": article_type, "types": publication_types, "retracted": retracted,
"doi": doi, "year": year, "authors": authors, "journal": journal,
"id": main_id, "pmid": pmid, "pmcid": pmcid})
Expand Down Expand Up @@ -398,14 +402,19 @@ def _merge_locked_shards(main_conn, shard_dbs, delete_after_merge, to_record):

embedding_text = paper_embedding_column(main_conn, shard_alias)

if main_cur.execute(f"SELECT 1 FROM {shard_alias}.sqlite_master WHERE name='build_sources'").fetchone():
from litkit.portable.record import SOURCE_SCHEMA
main_cur.execute(SOURCE_SCHEMA)
main_cur.execute(f"INSERT OR IGNORE INTO build_sources SELECT * FROM {shard_alias}.build_sources")
# 1) BULK MERGE PAPERS
# Insert papers that don't already exist (by doc_id)
main_cur.execute(f"""
INSERT OR IGNORE INTO papers(
doc_id, pmid, pmcid, doi, year, authors, journal, title, abstract, source_path, embedding_text, references_json, publication_source, article_type, publication_types, retracted, in_index
doc_id, pmid, pmcid, doi, year, authors, journal, title, abstract, source_path, embedding_text, references_json, license, license_url, build_member, publication_source, article_type, publication_types, retracted, in_index
)
SELECT p.doc_id, p.pmid, p.pmcid, {p_cols['doi']}, {p_cols['year']}, {p_cols['authors']}, {p_cols['journal']},
p.title, p.abstract, {source_path}, {embedding_text}, {p_cols['references_json']},
{p_cols['license']}, {p_cols['license_url']}, {p_cols['build_member']},
{p_cols['publication_source']}, {p_cols['article_type']}, {p_cols['publication_types']}, {p_cols['retracted']}, 0
FROM {shard_alias}.papers p
WHERE p.doc_id IS NOT NULL
Expand Down
3 changes: 3 additions & 0 deletions src/litkit/embeddings/sbert_mpnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,11 @@ def __init__(self, devices: list[str] | None = None, workers: int = 1):
if self.workers > 0 and len(self.devices) > self.workers:
self.devices = self.devices[: self.workers]

self.model_id = SBERT_ID
model_path = local_snapshot_dir(SBERT_ID) # must exist for offline runs

self.revision = model_path.name

# Multi-GPU only when >1 CUDA device
multi_gpu = len(self.devices) > 1 and self.devices[0].startswith("cuda")
options = safe_weight_options(model_path)
Expand Down
1 change: 1 addition & 0 deletions src/litkit/embeddings/specter2.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ def __init__(
self.model_id = model_id
self.device = device or detect_device()
local_path = local_snapshot_dir(self.model_id)
self.revision = local_path.name
self.tok, self.model = load_auto_or_fallback(local_path, device=self.device)
self.model.eval()

Expand Down
13 changes: 9 additions & 4 deletions src/litkit/index/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,19 @@ def _assert_faiss_locked() -> None:
)


def _write_index_atomically(index: faiss.Index, path: Path) -> None:
tmp = path.with_suffix(path.suffix + ".tmp")
def write_index(index: faiss.Index, path: Path) -> None:
"""Write to a caller-owned file, including Unicode paths on Windows."""
if os.name == "nt":
# FAISS 1.8 uses narrow filenames on Windows. Python opens Unicode paths.
with tmp.open("wb") as stream:
with path.open("wb") as stream:
faiss.write_index(index, faiss.PyCallbackIOWriter(stream.write))
else:
faiss.write_index(index, str(tmp))
faiss.write_index(index, str(path))


def _write_index_atomically(index: faiss.Index, path: Path) -> None:
tmp = path.with_suffix(path.suffix + ".tmp")
write_index(index, tmp)

# fsync the temp file before rename for durability
try:
Expand Down
9 changes: 9 additions & 0 deletions src/litkit/ingest/ingest.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,8 @@ class ArticleMeta(TypedDict):
abstract: str
paragraphs: list[str]
source_path: NotRequired[str]
license: NotRequired[str]
license_url: NotRequired[str]
article_type: NotRequired[str]
publication_types: NotRequired[list[str]]
retracted: NotRequired[bool]
Expand Down Expand Up @@ -1138,6 +1140,13 @@ def _walk_root(node: etree._Element) -> None:
"abstract": abstract or "",
"paragraphs": paras,
}
from litkit.portable.record import jats_license

license_name, license_url = jats_license(root.find("{*}front/{*}article-meta"))
if license_name:
meta["license"] = license_name
if license_url:
meta["license_url"] = license_url
from litkit.ingest.publication_types import classify

raw_type = root.get("article-type", "")
Expand Down
1 change: 1 addition & 0 deletions src/litkit/portable/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Vector release, source reconstruction and on-demand retrieval."""
Loading
Loading