|
| 1 | +from pathlib import Path |
| 2 | +from typing import Dict, List, Tuple |
| 3 | + |
| 4 | +from fire import Fire |
| 5 | +from pydantic import BaseModel |
| 6 | +from tqdm import tqdm |
| 7 | +from transformers import AutoTokenizer |
| 8 | + |
| 9 | +from transformer_base import run_summarization |
| 10 | +from utils import RelationData, RelationSentence |
| 11 | + |
| 12 | + |
| 13 | +class Encoder(BaseModel): |
| 14 | + def encode_x(self, x: str) -> str: |
| 15 | + raise NotImplementedError |
| 16 | + |
| 17 | + def encode(self, sent: RelationSentence) -> Tuple[str, str]: |
| 18 | + raise NotImplementedError |
| 19 | + |
| 20 | + def decode(self, x: str, y: str) -> RelationSentence: |
| 21 | + raise NotImplementedError |
| 22 | + |
| 23 | + def decode_x(self, x: str) -> str: |
| 24 | + raise NotImplementedError |
| 25 | + |
| 26 | + def safe_decode(self, x: str, y: str) -> RelationSentence: |
| 27 | + text = self.decode_x(x) |
| 28 | + try: |
| 29 | + s = self.decode(x=x, y=y) |
| 30 | + except Exception as e: |
| 31 | + s = RelationSentence( |
| 32 | + tokens=text.split(), head=[], tail=[], label="", error=str(e), raw=y |
| 33 | + ) |
| 34 | + return s |
| 35 | + |
| 36 | + def encode_to_line(self, sent: RelationSentence) -> str: |
| 37 | + raise NotImplementedError |
| 38 | + |
| 39 | + def decode_from_line(self, line: str) -> RelationSentence: |
| 40 | + raise NotImplementedError |
| 41 | + |
| 42 | + def parse_line(self, line: str) -> Tuple[str, str]: |
| 43 | + raise NotImplementedError |
| 44 | + |
| 45 | + |
| 46 | +class GenerateEncoder(Encoder): |
| 47 | + def encode_x(self, r: str) -> str: |
| 48 | + return f"Relation : {r} ." |
| 49 | + |
| 50 | + def decode_x(self, text: str) -> str: |
| 51 | + return text.split("Relation : ")[-1][:-2] |
| 52 | + |
| 53 | + def encode_triplet(self, sent: RelationSentence) -> str: |
| 54 | + s, r, o = sent.as_tuple() |
| 55 | + return f"Context : {sent.text} Head Entity : {s} , Tail Entity : {o} ." |
| 56 | + |
| 57 | + def decode_triplet(self, text: str, label: str) -> RelationSentence: |
| 58 | + front, back = text.split(" Head Entity : ") |
| 59 | + _, context = front.split("Context : ") |
| 60 | + head, back = back.split(" , Tail Entity : ") |
| 61 | + tail = back[:-2] |
| 62 | + return RelationSentence.from_spans(context, head, tail, label) |
| 63 | + |
| 64 | + def encode_y(self, sent: RelationSentence) -> str: |
| 65 | + return self.encode_x(sent.label) + " " + self.encode_triplet(sent) |
| 66 | + |
| 67 | + def decode_y(self, text: str, label: str) -> RelationSentence: |
| 68 | + del label |
| 69 | + front, back = text.split(" . Context : ") |
| 70 | + label = self.decode_x(front + " .") |
| 71 | + return self.decode_triplet("Context : " + back, label) |
| 72 | + |
| 73 | + def decode(self, x: str, y: str) -> RelationSentence: |
| 74 | + r = self.decode_x(x) |
| 75 | + sent = self.decode_y(y, r) |
| 76 | + return sent |
| 77 | + |
| 78 | + def encode(self, sent: RelationSentence) -> Tuple[str, str]: |
| 79 | + x = self.encode_x(sent.label) |
| 80 | + y = self.encode_y(sent) |
| 81 | + return x, y |
| 82 | + |
| 83 | + def decode_from_line(self, line: str) -> RelationSentence: |
| 84 | + x, y = self.parse_line(line) |
| 85 | + return self.decode(x, y) |
| 86 | + |
| 87 | + def encode_to_line(self, sent: RelationSentence) -> str: |
| 88 | + x, y = self.encode(sent) |
| 89 | + return y + "\n" |
| 90 | + |
| 91 | + def parse_line(self, line: str) -> Tuple[str, str]: |
| 92 | + return "", line.strip() |
| 93 | + |
| 94 | + |
| 95 | +class ExtractEncoder(Encoder): |
| 96 | + def encode_x(self, text: str) -> str: |
| 97 | + return f"Context : {text}" |
| 98 | + |
| 99 | + def decode_x(self, x: str) -> str: |
| 100 | + return x.split("Context : ")[-1] |
| 101 | + |
| 102 | + def encode_y(self, sent: RelationSentence) -> str: |
| 103 | + s, r, o = sent.as_tuple() |
| 104 | + return f"Head Entity : {s} , Tail Entity : {o} , Relation : {r} ." |
| 105 | + |
| 106 | + def decode_y(self, x: str, y: str) -> RelationSentence: |
| 107 | + context = self.decode_x(x) |
| 108 | + front, label = y.split(" , Relation : ") |
| 109 | + label = label[:-2] |
| 110 | + front, tail = front.split(" , Tail Entity : ") |
| 111 | + _, head = front.split("Head Entity : ") |
| 112 | + return RelationSentence.from_spans(context, head, tail, label) |
| 113 | + |
| 114 | + def encode_entity_prompt(self, head: str, tail: str) -> str: |
| 115 | + return f"Head Entity : {head} , Tail Entity : {tail} , Relation :" |
| 116 | + |
| 117 | + def encode(self, sent: RelationSentence) -> Tuple[str, str]: |
| 118 | + x = self.encode_x(sent.text) |
| 119 | + y = self.encode_y(sent) |
| 120 | + return x, y |
| 121 | + |
| 122 | + def decode(self, x: str, y: str) -> RelationSentence: |
| 123 | + return self.decode_y(x, y) |
| 124 | + |
| 125 | + def encode_to_line(self, sent: RelationSentence) -> str: |
| 126 | + x, y = self.encode(sent) |
| 127 | + return run_summarization.encode_to_line(x, y) |
| 128 | + |
| 129 | + def decode_from_line(self, line: str) -> RelationSentence: |
| 130 | + x, y = self.parse_line(line) |
| 131 | + return self.decode(x, y) |
| 132 | + |
| 133 | + def parse_line(self, line: str) -> Tuple[str, str]: |
| 134 | + return run_summarization.decode_from_line(line) |
| 135 | + |
| 136 | + |
| 137 | +def test_encoders( |
| 138 | + paths: List[str] = [ |
| 139 | + "outputs/data/zsl/wiki/unseen_5_seed_0/train.jsonl", |
| 140 | + "outputs/data/zsl/fewrel/unseen_5_seed_0/train.jsonl", |
| 141 | + ], |
| 142 | + print_limit: int = 4, |
| 143 | + encoder_names: List[str] = ["generate", "extract"], |
| 144 | + limit: int = 1000, |
| 145 | +): |
| 146 | + encoders = {k: select_encoder(k) for k in encoder_names} |
| 147 | + |
| 148 | + for p in paths: |
| 149 | + data = RelationData.load(Path(p)) |
| 150 | + _, data = data.train_test_split(min(limit, len(data.sents)), random_seed=0) |
| 151 | + |
| 152 | + for name, e in tqdm(list(encoders.items())): |
| 153 | + num_fail = 0 |
| 154 | + print(dict(name=name, p=p)) |
| 155 | + for s in data.sents: |
| 156 | + encoded = e.encode_to_line(s) |
| 157 | + x, y = e.parse_line(encoded) |
| 158 | + decoded: RelationSentence = e.safe_decode(x, y) |
| 159 | + |
| 160 | + if decoded.as_tuple() != s.as_tuple(): |
| 161 | + if num_fail < print_limit: |
| 162 | + print(dict(gold=s.as_tuple(), text=s.text)) |
| 163 | + print(dict(pred=decoded.as_tuple(), text=decoded.text)) |
| 164 | + print(dict(x=x, y=y, e=decoded.error)) |
| 165 | + print() |
| 166 | + num_fail += 1 |
| 167 | + |
| 168 | + print(dict(success_rate=1 - (num_fail / len(data.sents)))) |
| 169 | + print("#" * 80) |
| 170 | + |
| 171 | + |
| 172 | +def select_encoder(name: str) -> Encoder: |
| 173 | + mapping: Dict[str, Encoder] = dict( |
| 174 | + extract=ExtractEncoder(), |
| 175 | + generate=GenerateEncoder(), |
| 176 | + ) |
| 177 | + encoder = mapping[name] |
| 178 | + return encoder |
| 179 | + |
| 180 | + |
| 181 | +def test_entity_prompts( |
| 182 | + path: str = "outputs/data/zsl/wiki/unseen_10_seed_0/test.jsonl", limit: int = 100 |
| 183 | +): |
| 184 | + def tokenize(text: str, tok) -> List[str]: |
| 185 | + return tok.convert_ids_to_tokens(tok(text, add_special_tokens=False).input_ids) |
| 186 | + |
| 187 | + data = RelationData.load(Path(path)) |
| 188 | + e = ExtractEncoder() |
| 189 | + tokenizer = AutoTokenizer.from_pretrained("facebook/bart-base") |
| 190 | + print(tokenizer) |
| 191 | + for i, s in enumerate(tqdm(data.sents[:limit])): |
| 192 | + head, label, tail = s.as_tuple() |
| 193 | + x, y = e.encode(s) |
| 194 | + prompt = e.encode_entity_prompt(head, tail) |
| 195 | + tokens_y = tokenize(y, tokenizer) |
| 196 | + tokens_prompt = tokenize(prompt, tokenizer) |
| 197 | + assert tokens_y[: len(tokens_prompt)] == tokens_prompt |
| 198 | + if i < 3: |
| 199 | + print(tokens_y) |
| 200 | + |
| 201 | + |
| 202 | +if __name__ == "__main__": |
| 203 | + Fire() |
0 commit comments