-
Notifications
You must be signed in to change notification settings - Fork 5
feat(indexers): add framework for default hooks #140
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
5213d82
feat(indexers): add framework for flexible, common hooks to be providβ¦
lukeroantreeONS 96cda0b
Merge branch 'main' into 139-default-hooks
lukeroantreeONS f3fd636
feat(hooks): add deduplication postprocessing hook, refactor base claβ¦
lukeroantreeONS 4365bda
docs(hooks): improved docstring in CapitalisationStandardisingHook
lukeroantreeONS b438b12
feat(hooks): allow multiple columns to be passed to CapitalisationStaβ¦
lukeroantreeONS 565a707
fix(hooks): make deduplicated ranking start from 1 not 0
lukeroantreeONS 6a03300
chore(hooks): rerank in duplcation based on new score not new rank, tβ¦
lukeroantreeONS 37f4c8d
feat(hooks): let each hook type be a list of hooks or individual hookβ¦
lukeroantreeONS 01c7221
chore(hooks): update .svg files for demo, add missing Markdown paragrβ¦
lukeroantreeONS File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
692 changes: 0 additions & 692 deletions
692
DEMO/custom_preprocessing_and_postprocessing_hooks.ipynb
This file was deleted.
Oops, something went wrong.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| from .default_hooks import CapitalisationStandardisingHook, DeduplicationHook | ||
| from .hook_factory import HookBase | ||
|
|
||
| __all__ = [ | ||
| "CapitalisationStandardisingHook", | ||
| "DeduplicationHook", | ||
| "HookBase", | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| from .postprocessing import DeduplicationHook | ||
| from .preprocessing import CapitalisationStandardisingHook | ||
|
|
||
| __all__ = [ | ||
| "CapitalisationStandardisingHook", | ||
| "DeduplicationHook", | ||
| ] |
70 changes: 70 additions & 0 deletions
70
src/classifai/indexers/hooks/default_hooks/postprocessing.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| import numpy as np | ||
| import pandas as pd | ||
|
|
||
| from classifai.exceptions import HookError | ||
| from classifai.indexers.dataclasses import VectorStoreSearchOutput | ||
| from classifai.indexers.hooks.hook_factory import HookBase | ||
|
|
||
|
|
||
| class DeduplicationHook(HookBase): | ||
| """A pre-processing hook to remove duplicate knowledgebase entries, i.e. entries with the same label.""" | ||
|
|
||
| def _mean_score(self, scores): | ||
| return np.mean(scores) | ||
|
|
||
| def _max_score(self, scores): | ||
| return np.max(scores) | ||
|
|
||
| def __init__(self, score_aggregation_method: str = "max"): | ||
| """Inititialises the hook with the specified method for assigning scores to deduplicated entries. | ||
|
|
||
| Args: | ||
| score_aggregation_method (str): Method for assigning score to the deduplicated entry. | ||
| Must be one of "max" or "mean". Defaults to "max". | ||
| A future update will introduce a 'softmax' option. | ||
| """ | ||
| if score_aggregation_method not in ["max", "mean"]: | ||
| raise HookError( | ||
| "Invalid method for DeduplicationHook. Must be one of 'max', or 'mean'.", | ||
| context={self.hook_type: "Deduplication", "method": score_aggregation_method}, | ||
| ) | ||
| self.score_aggregation_method = score_aggregation_method | ||
| if self.score_aggregation_method == "max": | ||
| self.score_aggregator = self._max_score | ||
| elif self.score_aggregation_method == "mean": | ||
| self.score_aggregator = self._mean_score | ||
|
|
||
| super().__init__(hook_type="post_processing") | ||
|
|
||
| def __call__(self, input_data: VectorStoreSearchOutput) -> VectorStoreSearchOutput: | ||
| """Aggregates retrieved knowledgebase entries corresponding to the same label.""" | ||
| # 1) Group on two levels - first on query_id, then on doc_id, to ensure that entries with the same label are | ||
| # deduplicated within the results for each query. Note that there is a 1-1 mapping between query_id and query_text, | ||
| # so no extra grouping is made, but this excludes query_text from the columns to be processed. | ||
| # 2) For each group, aggregate the score using the specified method, and assign a new column 'idxmax' to the unique id | ||
| # of the entry with the best score. This will allow us to retain the metadata of the best scoring entry. | ||
| df_gpby = ( | ||
| input_data.groupby(["query_id", "query_text", "doc_id"]) | ||
| .aggregate( | ||
| score=("score", self.score_aggregator), | ||
| idxmax=("score", "idxmax"), | ||
| rank=("rank", "min"), | ||
| ) | ||
| .reset_index() | ||
| ) | ||
| # For each query, re-assign ranks based on the new aggregated scores, to the remaining entries, to ensure that the best | ||
| # scoring entry for each label is ranked highest. | ||
| for query in df_gpby["query_id"].unique(): | ||
| batch = df_gpby[df_gpby["query_id"] == query] | ||
| new_rank = pd.factorize(-batch["score"], sort=True)[0] + 1 | ||
| df_gpby.loc[batch.index, "rank"] = new_rank | ||
| # Finally, we re-merge the deduplicated results with the original input dataframe, | ||
| # to retrieve the metadata of the best scoring entry for each label, and return the processed output. | ||
| for col in set(input_data.columns).difference(set(df_gpby.columns)): | ||
| df_gpby[col] = df_gpby["idxmax"].map(input_data[col]) | ||
| # We sort the output by query_id and doc_id to ensure a consistent order of results for each query, | ||
| # and validate the output against the dataclass schema. | ||
| processed_output = input_data.__class__.validate( | ||
| df_gpby[input_data.columns].sort_values(by=["query_id", "doc_id"], ascending=[True, True]) | ||
| ) | ||
| return processed_output |
63 changes: 63 additions & 0 deletions
63
src/classifai/indexers/hooks/default_hooks/preprocessing.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| from classifai.exceptions import HookError | ||
| from classifai.indexers.dataclasses import ( | ||
| VectorStoreEmbedInput, | ||
| VectorStoreReverseSearchInput, | ||
| VectorStoreSearchInput, | ||
| ) | ||
| from classifai.indexers.hooks.hook_factory import HookBase | ||
|
|
||
|
|
||
| class CapitalisationStandardisingHook(HookBase): | ||
| """A pre-processing hook to handle upper-/lower-/sentence-/title-casing.""" | ||
|
|
||
| def __init__(self, method: str = "lower", colname: str | list[str] = "query"): | ||
| """Inititialises the hook with the specified method for standardising capitalisation. | ||
|
|
||
| Args: | ||
| method (str): Method for standardisation. Must be one of "lower" (like this), | ||
| "upper" (LIKE THIS), "sentence" (Like this), or "title" (Like This). | ||
| Defaults to "lower". | ||
| colname (str | list[str]): The name of one of the fields of the Input object which is/are | ||
| to be capitalised. | ||
| Defaults to "query". | ||
| """ | ||
| super().__init__(method=method, colname=colname, hook_type="pre_processing") | ||
| if method not in {"lower", "upper", "sentence", "title"}: | ||
| raise HookError( | ||
| "Invalid method for CapitalisationStandardisingHook. " | ||
| "Must be one of 'lower', 'upper', 'sentence', or 'title'.", | ||
| context={self.hook_type: "Capitalisation", "method": method}, | ||
| ) | ||
| if method == "lower": | ||
| self.method = str.lower | ||
| elif method == "upper": | ||
| self.method = str.upper | ||
| elif method == "sentence": | ||
| self.method = lambda text: text.capitalize() if text else text | ||
| elif method == "title": | ||
| self.method = str.title | ||
| self.colname = colname | ||
|
|
||
| def __call__( | ||
| self, input_data: VectorStoreSearchInput | VectorStoreReverseSearchInput | VectorStoreEmbedInput | ||
| ) -> VectorStoreSearchInput | VectorStoreReverseSearchInput | VectorStoreEmbedInput: | ||
| """Standardises capitalisation in the input data as specified by 'method' attribute.""" | ||
| if isinstance(self.colname, str): | ||
| self.colname = [self.colname] | ||
| for col in self.colname: | ||
| if col not in input_data.columns: | ||
| raise HookError( | ||
| "Invalid column name passed.", context={"pre_processing": "Capitalisation", "colname": col} | ||
| ) | ||
| if col not in input_data.select_dtypes(include=["object"]).columns: | ||
| raise HookError( | ||
| f"colname is of type {input_data[col].dtype}, expected 'str'.", | ||
| context={"pre_processing": "Capitalisation", "colname": col}, | ||
| ) | ||
|
|
||
| processed_input = input_data.copy() | ||
| for col in self.colname: | ||
| processed_input[col] = processed_input[col].apply(self.method) | ||
| # Ensure the processed input still conforms to the schema | ||
| processed_input = input_data.__class__.validate(processed_input) | ||
| return processed_input |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| from abc import ABC, abstractmethod | ||
|
|
||
| from classifai.exceptions import HookError | ||
| from classifai.indexers.dataclasses import ( | ||
| VectorStoreEmbedInput, | ||
| VectorStoreEmbedOutput, | ||
| VectorStoreReverseSearchInput, | ||
| VectorStoreReverseSearchOutput, | ||
| VectorStoreSearchInput, | ||
| VectorStoreSearchOutput, | ||
| ) | ||
|
|
||
|
|
||
| class HookBase(ABC): | ||
| """Abstract base class for all post-processing hooks requiring customisation.""" | ||
|
|
||
| def __init__(self, **kwargs): | ||
lukeroantreeONS marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| """Sets any attributes required by the hook.""" | ||
| self.hook_type: str = "generic" # Placeholder for hook type, can be overridden by subclasses | ||
lukeroantreeONS marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| # or set via kwargs | ||
| self.kwargs = kwargs | ||
|
|
||
| @abstractmethod | ||
| def __call__( | ||
| self, | ||
| data: VectorStoreSearchOutput | ||
| | VectorStoreReverseSearchOutput | ||
| | VectorStoreEmbedOutput | ||
| | VectorStoreSearchInput | ||
| | VectorStoreReverseSearchInput | ||
| | VectorStoreEmbedInput, | ||
| ) -> ( | ||
| VectorStoreSearchOutput | ||
| | VectorStoreReverseSearchOutput | ||
| | VectorStoreEmbedOutput | ||
| | VectorStoreSearchInput | ||
| | VectorStoreReverseSearchInput | ||
| | VectorStoreEmbedInput | ||
| ): | ||
| """Defines the behavior of the hook when called.""" | ||
| processed_data = data # Placeholder for processing logic | ||
| if not isinstance(processed_data, type(data)): | ||
| raise HookError( | ||
| f"Processed data must be of the same type as input. " | ||
| f"Expected {type(data).__name__}, got {type(processed_data).__name__}.", | ||
| context={"hook_type": self.hook_type}, | ||
| ) | ||
| return processed_data | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.