Coverage for corgi/modules.py: 100.00%
71 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-28 00:24 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-28 00:24 +0000
1"""Lightning module for Corgi with support for saving embeddings during prediction."""
3from pathlib import Path
4from torchapp.modules import GeneralLightningModule
5import numpy as np
6import os
7from rich.console import Console
9console = Console()
12class CorgiLightningModule(GeneralLightningModule):
13 """A Lightning module which can write the model's embeddings to a memory-mapped file during prediction."""
15 def __init__(self, *args, **kwargs):
16 """Initializes the module with no embeddings output."""
17 super().__init__(*args, **kwargs)
18 self.embeddings_path = None
19 self.embeddings = None
20 self.dataloader = None
21 self.current_position = 0
23 def set_embedding_path(self, embeddings_path: Path | str, dataloader):
24 """
25 Set the path for the memmap array and initialize it if necessary.
26 """
27 self.embeddings_path = Path(embeddings_path)
28 self.dataloader = dataloader
30 def on_predict_epoch_end(self):
31 """Flushes the embeddings to disk and writes an index file beside them.
33 The index has a line with the file and record ID (tab-separated) for each chunk.
34 """
35 if self.embeddings is not None:
36 self.embeddings.flush()
37 del self.embeddings
38 self.embeddings = None
39 self.current_position = 0
41 # Write the memmap index
42 embeddings_index = self.embeddings_path.with_suffix('.index')
43 console.print(f"Exporting embeddings to '{self.embeddings_path}'")
44 console.print(f"Exporting memmap index to '{embeddings_index}'")
45 with open(embeddings_index, 'w') as f:
46 for file, record_id, _, _ in self.dataloader.chunk_details:
47 # Replace pipe with underscore for file names
48 file = str(file).replace("\t", "_")
49 record_id = str(record_id).replace("\t", "_")
50 f.write(f"{file}\t{record_id}\n")
52 def predict_step(self, batch):
53 """Returns the model's predictions for a batch, saving the embeddings if an embeddings path was set.
55 Args:
56 batch (tuple): The inputs for the model.
57 """
58 assert isinstance(batch, tuple)
59 assert len(batch) >= self.input_count
60 x = batch[: self.input_count]
62 self.model.return_embeddings = self.embeddings_path is not None
63 if not self.model.return_embeddings:
64 result = self(*x)
65 else:
66 result, embedding = self(*x)
68 # Create memmap array if it is the first time
69 embedding = embedding.half().cpu().numpy()
70 if self.embeddings is None:
71 self.embeddings_path.parent.mkdir(parents=True, exist_ok=True)
72 shape = (self.dataloader.count, embedding.shape[-1])
73 self.embeddings = np.memmap(self.embeddings_path, dtype=embedding.dtype, mode='w+', shape=shape)
74 self.current_position = 0
76 # Save embeddings to memmap
77 batch_size = len(x[0])
78 self.embeddings[self.current_position : self.current_position + batch_size, :] = embedding
79 self.current_position += batch_size
81 # Return result of the model
82 return result
85def read_memmap(path, count, dtype: str = "float16") -> np.memmap:
86 """Opens a memory-mapped array of embeddings.
88 Args:
89 path: The path to the embeddings file.
90 count (int): The number of embeddings (rows) in the file.
91 dtype (str): The data type stored in the file.
92 """
93 file_size = os.path.getsize(path)
94 dtype_size = np.dtype(dtype).itemsize
95 num_elements = file_size // dtype_size
96 embedding_size = num_elements // count
97 shape = (count, embedding_size)
98 return np.memmap(path, dtype=dtype, mode='r', shape=shape)
101def read_embeddings(
102 embeddings_path: Path | str, embeddings_index: Path = None, merge: bool = True
103) -> tuple[np.ndarray, list[str]]:
104 """
105 Read embeddings from a memmap file.
106 """
107 embeddings_path = Path(embeddings_path)
108 index_path = embeddings_index or embeddings_path.with_suffix('.index')
109 index_path = Path(index_path)
110 assert index_path.exists(), f"Index file '{index_path}' does not exist."
111 index_with_tabs = Path(index_path).read_text().strip().splitlines()
113 embeddings = read_memmap(embeddings_path, len(index_with_tabs))
115 if merge:
116 import pandas as pd
118 df = pd.DataFrame(embeddings)
119 df["index_with_tabs"] = index_with_tabs
121 # Group by 'index_with_tabs' and average the embeddings
122 grouped = df.groupby("index_with_tabs", sort=False).mean(numeric_only=True)
124 # Extract the averaged embeddings and the corresponding unique ids
125 embeddings = grouped.values
126 index_with_tabs = grouped.index.to_list()
128 index = [line.split("\t") for line in index_with_tabs]
130 return embeddings, index