kapipe 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. kapipe/__init__.py +39 -0
  2. kapipe/datatypes/__init__.py +11 -0
  3. kapipe/datatypes/datatypes.py +69 -0
  4. kapipe/decoders/__init__.py +6 -0
  5. kapipe/decoders/spanbaseddecoder.py +97 -0
  6. kapipe/demonstration_retrievers/__init__.py +1 -0
  7. kapipe/demonstration_retrievers/demonstration_retrievers.py +85 -0
  8. kapipe/evaluation/__init__.py +3 -0
  9. kapipe/evaluation/docre/__init__.py +4 -0
  10. kapipe/evaluation/docre/docred_official.py +610 -0
  11. kapipe/evaluation/docre/fscore.py +261 -0
  12. kapipe/evaluation/ed/__init__.py +5 -0
  13. kapipe/evaluation/ed/accuracy.py +116 -0
  14. kapipe/evaluation/ed/fscore.py +155 -0
  15. kapipe/evaluation/ed/recall_at_k.py +96 -0
  16. kapipe/evaluation/ner/__init__.py +1 -0
  17. kapipe/evaluation/ner/fscore.py +189 -0
  18. kapipe/misc/__init__.py +3 -0
  19. kapipe/misc/anns.py +54 -0
  20. kapipe/misc/bm25.py +168 -0
  21. kapipe/misc/textsimretriever.py +108 -0
  22. kapipe/models/__init__.py +14 -0
  23. kapipe/models/atlop_model.py +1629 -0
  24. kapipe/models/biaffinener_model.py +775 -0
  25. kapipe/models/entityrerankingcrossencoder_model.py +566 -0
  26. kapipe/models/entityretrievalbiencoder_model.py +1097 -0
  27. kapipe/models/llm.py +394 -0
  28. kapipe/models/losses/__init__.py +4 -0
  29. kapipe/models/losses/adaptivethresholding.py +93 -0
  30. kapipe/models/losses/focal.py +74 -0
  31. kapipe/models/losses/marginalizedcrossentropy.py +51 -0
  32. kapipe/models/maatlop_model.py +961 -0
  33. kapipe/models/maqa_model.py +818 -0
  34. kapipe/models/shared_functions.py +233 -0
  35. kapipe/pipeline.py +694 -0
  36. kapipe/prompt_processors/__init__.py +5 -0
  37. kapipe/prompt_processors/docre_prompt_processor_v4.py +344 -0
  38. kapipe/prompt_processors/ed_prompt_processor_v5.py +395 -0
  39. kapipe/prompt_processors/ner_prompt_processor_v5.py +307 -0
  40. kapipe/prompt_processors/prompt_templates/__init__.py +0 -0
  41. kapipe/systems/__init__.py +15 -0
  42. kapipe/systems/atlop_system.py +266 -0
  43. kapipe/systems/biaffinener_system.py +298 -0
  44. kapipe/systems/entityrerankingcrossencoder_system.py +279 -0
  45. kapipe/systems/entityretrievalbiencoder_system.py +453 -0
  46. kapipe/systems/lexicalentityretrieval_system.py +234 -0
  47. kapipe/systems/llmdocre_system.py +239 -0
  48. kapipe/systems/llmed_system.py +324 -0
  49. kapipe/systems/llmner_system.py +215 -0
  50. kapipe/systems/maatlop_system.py +394 -0
  51. kapipe/systems/maqa_system.py +250 -0
  52. kapipe/trainers/__init__.py +15 -0
  53. kapipe/trainers/atlop_trainer.py +561 -0
  54. kapipe/trainers/biaffinener_trainer.py +402 -0
  55. kapipe/trainers/entityrerankingcrossencoder_trainer.py +451 -0
  56. kapipe/trainers/entityretrievalbiencoder_trainer.py +584 -0
  57. kapipe/trainers/lexicalentityretrieval_trainer.py +143 -0
  58. kapipe/trainers/llmdocre_trainer.py +278 -0
  59. kapipe/trainers/llmed_trainer.py +174 -0
  60. kapipe/trainers/llmner_trainer.py +144 -0
  61. kapipe/trainers/maatlop_trainer.py +580 -0
  62. kapipe/trainers/maqa_trainer.py +587 -0
  63. kapipe/trainers/shared_functions.py +220 -0
  64. kapipe/utils.py +308 -0
  65. kapipe-0.0.1.dist-info/LICENSE +202 -0
  66. kapipe-0.0.1.dist-info/METADATA +526 -0
  67. kapipe-0.0.1.dist-info/RECORD +69 -0
  68. kapipe-0.0.1.dist-info/WHEEL +5 -0
  69. kapipe-0.0.1.dist-info/top_level.txt +1 -0
kapipe/__init__.py ADDED
@@ -0,0 +1,39 @@
1
+ # Types defined
2
+ from . import datatypes
3
+
4
+ # Top-level modules
5
+ from . import systems
6
+
7
+ # Submodules for `systems`
8
+ from . import models
9
+ from . import decoders
10
+ from . import prompt_processors
11
+ from . import misc
12
+
13
+ # Top modules for training and evaluation
14
+ from . import trainers
15
+
16
+ # Evaluation metrics
17
+ from . import evaluation
18
+
19
+ # Retrievers for few-shot in-context learning
20
+ from . import demonstration_retrievers
21
+
22
+ from . import utils
23
+
24
+
25
+ from .pipeline import Pipeline
26
+
27
+
28
+ __version__ = "0.0.1"
29
+
30
+
31
+ def load(identifier, gpu_map=None):
32
+ ka = Pipeline(identifier=identifier, gpu_map=gpu_map)
33
+ return ka
34
+
35
+
36
+ def blank(gpu_map=None):
37
+ ka = Pipeline(identifier=None, gpu_map=gpu_map)
38
+ return ka
39
+
@@ -0,0 +1,11 @@
1
+ from .datatypes import DocKey
2
+ from .datatypes import Document
3
+ from .datatypes import Mention
4
+ from .datatypes import Entity
5
+ from .datatypes import Triple
6
+
7
+ from .datatypes import EntityPage
8
+ from .datatypes import CandEntKeyInfo
9
+ from .datatypes import EntDoc
10
+
11
+ from .datatypes import DemoKeyInfo
@@ -0,0 +1,69 @@
1
+ from typing import Any, TypeAlias
2
+
3
+
4
+ DocKey : TypeAlias = str
5
+
6
+ Document : TypeAlias = dict[str, Any]
7
+ # {
8
+ # "doc_key": str,
9
+ # "sentences": list[str],
10
+ # "mentions": list[Mention],
11
+ # "entities": list[Entity],
12
+ # "relations": list[Triple]
13
+ # }
14
+
15
+ Mention : TypeAlias = dict[str, Any]
16
+ # {
17
+ # "span": tuple[int],
18
+ # "name": str,
19
+ # "entity_type": str
20
+ # }
21
+
22
+ Entity : TypeAlias = dict[str, Any]
23
+ # {
24
+ # "mention_indices": list[int],
25
+ # "entity_type": str,
26
+ # "entity_id": str
27
+ # }
28
+
29
+ Triple : TypeAlias = dict[str, Any]
30
+ # {
31
+ # "arg1": int,
32
+ # "relation": str,
33
+ # "arg2": int
34
+ # }
35
+
36
+ ##########
37
+ # For candidate entities in ED
38
+ ##########
39
+
40
+ EntityPage : TypeAlias = dict[str, Any]
41
+ # {
42
+ # "entity_id": str,
43
+ # "canonical_name": str,
44
+ # "synonyms": list[str],
45
+ # "description": str
46
+ # }
47
+
48
+ CandEntKeyInfo : TypeAlias = dict[str, Any]
49
+ # {
50
+ # "entity_id": str,
51
+ # "score": float
52
+ # }
53
+
54
+ EntDoc: TypeAlias = dict[str, str]
55
+ # {
56
+ # "entity_id": str,
57
+ # "canonical_name": str,
58
+ # "text": str
59
+ # }
60
+
61
+ ##########
62
+ # For in-context learning
63
+ ##########
64
+
65
+ DemoKeyInfo : TypeAlias = dict[str, Any]
66
+ # {
67
+ # "doc_key": str,
68
+ # "score": float
69
+ # }
@@ -0,0 +1,6 @@
1
+ # NER
2
+ from .spanbaseddecoder import SpanBasedDecoder
3
+
4
+ # Entity Linking
5
+
6
+ # DocRE
@@ -0,0 +1,97 @@
1
+ import numpy as np
2
+
3
+
4
+ class SpanBasedDecoder:
5
+ """A span-based decoder for NER. This decoder applies constraints (for either Flat NER or Nested NER) to given scored spans and outputs a list of mentions.
6
+ """
7
+
8
+ def __init__(
9
+ self,
10
+ allow_nested_entities
11
+ ):
12
+ """
13
+ Parameters
14
+ ----------
15
+ allow_nested_entities : bool
16
+ """
17
+ self.allow_nested_entities = allow_nested_entities
18
+
19
+ def decode(
20
+ self,
21
+ spans,
22
+ words
23
+ ):
24
+ """
25
+ Parameters
26
+ ----------
27
+ spans : list[tuple[int, int, str, float]]
28
+ words : list[str]
29
+
30
+ Results
31
+ -------
32
+ list[Mention]
33
+ """
34
+ mentions = [] # list[Mention]
35
+
36
+ # Sort the candidate spans based on their scores
37
+ spans = sorted(spans, key=lambda x: -x[-1])
38
+
39
+ # Select spans
40
+ n_words = len(words)
41
+ self.check_matrix = np.zeros((n_words, n_words)) # Used in Flat NER
42
+ self.check_set = set() # Uased in Nested NER
43
+ for span in spans:
44
+ begin_token_index, end_token_index, etype, _ = span
45
+ name = " ".join(words[begin_token_index: end_token_index + 1])
46
+ if self.is_violation(
47
+ begin_token_index=begin_token_index,
48
+ end_token_index=end_token_index
49
+ ):
50
+ continue
51
+ mentions.append({
52
+ "span": (begin_token_index, end_token_index),
53
+ "name": name,
54
+ "entity_type": etype,
55
+ })
56
+ self.check_matrix[begin_token_index: end_token_index + 1] = 1
57
+ self.check_set.add((begin_token_index, end_token_index))
58
+
59
+ # Sort mentions based on the positions
60
+ mentions = sorted(mentions, key=lambda m: m["span"])
61
+
62
+ return mentions
63
+
64
+ def is_violation(self, begin_token_index, end_token_index):
65
+ """
66
+ Parameters
67
+ ----------
68
+ begin_token_index : int
69
+ end_token_index : int
70
+
71
+ Returns
72
+ -------
73
+ bool
74
+ """
75
+ if not self.allow_nested_entities:
76
+ # Flat NER
77
+ if (
78
+ self.check_matrix[begin_token_index: end_token_index + 1].sum()
79
+ > 0
80
+ ):
81
+ return True
82
+ else:
83
+ return False
84
+ else:
85
+ # Nested NER
86
+ for begin_token_j, end_token_j in self.check_set:
87
+ if (
88
+ (begin_token_index < begin_token_j
89
+ <= end_token_index < end_token_j)
90
+ or
91
+ (begin_token_j < begin_token_index
92
+ <= end_token_j < end_token_index)
93
+ ):
94
+ return True
95
+ return False
96
+
97
+
@@ -0,0 +1 @@
1
+ from .demonstration_retrievers import DemonstrationRetriever
@@ -0,0 +1,85 @@
1
+ import random
2
+
3
+ from .. import utils
4
+
5
+
6
+ class DemonstrationRetriever:
7
+ """A demonstration (i.e., a few-shot examplers) retriever for LLM-based in-context learning methods. This retriever returns the few-shot examplers for a given document.
8
+ """
9
+
10
+ def __init__(
11
+ self,
12
+ path_demonstration_pool,
13
+ method,
14
+ task="docre"
15
+ ):
16
+ """
17
+ Parameters
18
+ ----------
19
+ path_demonstration_pool : str
20
+ method : str
21
+ task : str, optional
22
+ by default "docre"
23
+ """
24
+ assert method in ["first", "random"]
25
+
26
+ self.path_demonstration_pool = path_demonstration_pool
27
+ self.method = method
28
+ self.task = task
29
+
30
+ # Get a map from DocKey to Document
31
+ self.demonstration_pool = {
32
+ demo_doc["doc_key"]: demo_doc
33
+ for demo_doc in utils.read_json(self.path_demonstration_pool)
34
+ }
35
+
36
+ # Get a pool of candidate document keys for retrieval
37
+ self.doc_keys = list(self.demonstration_pool.keys())
38
+
39
+ def retrieve(self, document, top_k, doc_keys=None):
40
+ """
41
+ Parameters
42
+ ----------
43
+ document : Document
44
+ top_k : int
45
+ doc_keys : list[str] | None, optional
46
+ by default None
47
+
48
+ Returns
49
+ -------
50
+ dict[str, str | list[dict[str, str | float]]]
51
+ """
52
+ # `doc_keys` can be used for retrieval on limited candidates
53
+ if doc_keys is None:
54
+ doc_keys = self.doc_keys
55
+
56
+ # list[dict[str, str | float]]
57
+ if self.method == "first":
58
+ demonstrations_for_doc = doc_keys[:top_k]
59
+ demonstrations_for_doc = [
60
+ {
61
+ "doc_key": key,
62
+ "score": 1.0
63
+ }
64
+ for key in demonstrations_for_doc
65
+ ]
66
+ elif self.method == "random":
67
+ demonstrations_for_doc = random.sample(doc_keys, top_k)
68
+ demonstrations_for_doc = [
69
+ {
70
+ "doc_key": key,
71
+ "score": 1.0
72
+ }
73
+ for key in demonstrations_for_doc
74
+ ]
75
+ else:
76
+ raise Exception(f"Invalid method: {self.method}")
77
+
78
+ # dict[str, str | list[dict[str, str | float]]]
79
+ demonstrations_for_doc = {
80
+ "doc_key": document["doc_key"],
81
+ "demonstrations": demonstrations_for_doc,
82
+ }
83
+
84
+ return demonstrations_for_doc
85
+
@@ -0,0 +1,3 @@
1
+ from . import ner
2
+ from . import ed
3
+ from . import docre
@@ -0,0 +1,4 @@
1
+ from .fscore import fscore
2
+
3
+ from .docred_official import to_official
4
+ from .docred_official import official_evaluate