Delete data_prep.py
Browse files- data_prep.py +0 -266
data_prep.py
DELETED
|
@@ -1,266 +0,0 @@
|
|
| 1 |
-
from typing import List, Dict, Optional
|
| 2 |
-
from torch.utils.data import Dataset
|
| 3 |
-
import torch
|
| 4 |
-
from transformers import AutoTokenizer, AutoModel, AutoConfig
|
| 5 |
-
from torch.utils.data import Dataset, DataLoader
|
| 6 |
-
import torch.nn as nn
|
| 7 |
-
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
|
| 8 |
-
from sklearn.metrics import f1_score
|
| 9 |
-
import json
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
#Create data instance, words: tokenized word list, predicte_word_idx: index for predicte, labels: Semantic roles
|
| 14 |
-
!@dataclass
|
| 15 |
-
class SRLSample():
|
| 16 |
-
def __init__(self, words: List[str], predicate_word_idx: int, labels: List[str], predicate_form: Optional[str] = None):
|
| 17 |
-
self.words = words
|
| 18 |
-
self.predicate_word_idx = predicate_word_idx
|
| 19 |
-
self.labels = labels
|
| 20 |
-
self.predicate_form = predicate_form
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
#To Leah: SRL Sample is object for each dataset so we need another code for each instance(words, predicate_word_idx, labels) into list of SRLSample objects
|
| 24 |
-
|
| 25 |
-
def create_srl_samples(data_path):
|
| 26 |
-
samples = []
|
| 27 |
-
with open(data_path, 'r', encoding='utf-8') as f:
|
| 28 |
-
for line in f:
|
| 29 |
-
data = json.loads(line)
|
| 30 |
-
samples.append(SRLSample(**data))
|
| 31 |
-
|
| 32 |
-
return samples
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
#Example
|
| 36 |
-
|
| 37 |
-
#if __name__ == '__main__'
|
| 38 |
-
|
| 39 |
-
# data_class_train = create_srl_samples('/content/drive/MyDrive/Dissertation/srl_synthetic_100.jsonl')
|
| 40 |
-
|
| 41 |
-
# data_class_dev = create_srl_samples('/content/drive/MyDrive/Dissertation/srl_synthetic_dev_10.jsonl')
|
| 42 |
-
|
| 43 |
-
# data_class_test = create_srl_samples('/content/drive/MyDrive/Dissertation/srl_synthetic_test_10.jsonl')
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
class SRLDataset(Dataset):
|
| 47 |
-
"""
|
| 48 |
-
Expects samples at WORD-level. We build BERT inputs as:
|
| 49 |
-
[CLS] <sentence (wordpiece)> [SEP] <predicate (wordpiece)> [SEP]
|
| 50 |
-
We keep:
|
| 51 |
-
- wordpiece indices for each word's FIRST subtoken (to pool BERT to word level)
|
| 52 |
-
- sentence lengths
|
| 53 |
-
- predicate's WORD index within the sentence (for gp from BiLSTM outputs)
|
| 54 |
-
"""
|
| 55 |
-
def __init__(self, samples: List[SRLSample], tokenizer: AutoTokenizer, label2id: Dict[str, int], max_length: int = 256, debug_print= False):
|
| 56 |
-
self.samples = samples
|
| 57 |
-
self.tokenizer = tokenizer
|
| 58 |
-
self.label2id = label2id
|
| 59 |
-
self.id2label = {v: k for k, v in label2id.items()}
|
| 60 |
-
self.max_length = max_length
|
| 61 |
-
self.debug_print = debug_print
|
| 62 |
-
|
| 63 |
-
def __len__(self):
|
| 64 |
-
return len(self.samples)
|
| 65 |
-
|
| 66 |
-
def _tokenize_sentence(self, words: List[str]):
|
| 67 |
-
# Tokenize sentence as split words to preserve word boundaries
|
| 68 |
-
enc_sent = self.tokenizer(
|
| 69 |
-
words,
|
| 70 |
-
is_split_into_words=True,
|
| 71 |
-
add_special_tokens=False,
|
| 72 |
-
return_attention_mask=False,
|
| 73 |
-
return_token_type_ids=False
|
| 74 |
-
)
|
| 75 |
-
return enc_sent # dict with 'input_ids'
|
| 76 |
-
|
| 77 |
-
def _tokenize_predicate(self, form: str):
|
| 78 |
-
enc_pred = self.tokenizer(
|
| 79 |
-
form,
|
| 80 |
-
add_special_tokens=False,
|
| 81 |
-
return_attention_mask=False,
|
| 82 |
-
return_token_type_ids=False
|
| 83 |
-
)
|
| 84 |
-
return enc_pred
|
| 85 |
-
|
| 86 |
-
def __getitem__(self, idx):
|
| 87 |
-
|
| 88 |
-
instance = self.samples[idx]
|
| 89 |
-
words = instance.words
|
| 90 |
-
n_words = len(words)
|
| 91 |
-
assert 0 <= instance.predicate_word_idx < n_words, "Bad predicate index."
|
| 92 |
-
|
| 93 |
-
pred_form = instance.predicate_form if instance.predicate_form is not None else words[instance.predicate_word_idx]
|
| 94 |
-
|
| 95 |
-
# Tokenize sentence and predicate separately (Text -> numeric value)
|
| 96 |
-
enc_sent = self._tokenize_sentence(words)
|
| 97 |
-
enc_pred = self._tokenize_predicate(pred_form)
|
| 98 |
-
|
| 99 |
-
# print("This is enc_sent {}, this is enc_prec {} \n".format(enc_sent, enc_pred))
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
sent_wp_ids = enc_sent["input_ids"] # list[int]
|
| 103 |
-
pred_wp_ids = enc_pred["input_ids"] # list[int]
|
| 104 |
-
|
| 105 |
-
# Build final input ids and token type ids Here we added SEP for predicates create new input ids
|
| 106 |
-
# segment A (0): [CLS] sentence [SEP]
|
| 107 |
-
# segment B (1): predicate [SEP]
|
| 108 |
-
# [CLS] sentence [SEP] predicte [SEP]
|
| 109 |
-
# [CLS] sentence [SEP] ARG0_token [SEP] ARG1_token [SEP] ARG2_token [SEP] -> Model for emotion, formality and politeness
|
| 110 |
-
input_ids = [self.tokenizer.cls_token_id] + sent_wp_ids + [self.tokenizer.sep_token_id] \
|
| 111 |
-
+ pred_wp_ids + [self.tokenizer.sep_token_id]
|
| 112 |
-
|
| 113 |
-
# token_type_ids: 0 for [CLS] + sentence + [SEP], 1 for predicate + [SEP]
|
| 114 |
-
ttids = [0] * (1 + len(sent_wp_ids) + 1) + [1] * (len(pred_wp_ids) + 1)
|
| 115 |
-
|
| 116 |
-
# Build mapping: each WORD -> index of its FIRST wordpiece inside the FULL sequence
|
| 117 |
-
# We iterate tokenizer.word_ids() by re-tokenizing with special tokens for alignment
|
| 118 |
-
# Simpler: reconstruct with pre-known structure:
|
| 119 |
-
# [CLS] at 0; sentence starts at 1; we need mapping from word index to its FIRST wordpiece offset in `sent_wp_ids`.
|
| 120 |
-
# We'll align by re-tokenizing sentence with is_split_into_words and reading the mapping.
|
| 121 |
-
# HuggingFace trick: get word_ids requires encoding with add_special_tokens=True, so let's do that quickly:
|
| 122 |
-
tmp = self.tokenizer(words, is_split_into_words=True, return_offsets_mapping=False)
|
| 123 |
-
word_ids = tmp.word_ids()
|
| 124 |
-
# print("This is tmp {}, word_ids {}\n".format(tmp, word_ids))
|
| 125 |
-
# Now, tmp.input_ids == [CLS] + sent_wp + [SEP]; positions:
|
| 126 |
-
# 0: CLS, 1..1+len(sent_wp_ids)-1: sentence, 1+len(sent_wp_ids): SEP
|
| 127 |
-
# We need FIRST position per word_id in this tmp encoding.
|
| 128 |
-
first_wp_pos_in_full = []
|
| 129 |
-
seen = set()
|
| 130 |
-
for pos, wid in enumerate(word_ids):
|
| 131 |
-
if wid is None:
|
| 132 |
-
continue
|
| 133 |
-
if wid not in seen:
|
| 134 |
-
seen.add(wid)
|
| 135 |
-
first_wp_pos_in_full.append(pos) # pos in tmp sequence
|
| 136 |
-
# Sort by wid order to align [0..n_words-1]
|
| 137 |
-
# word_ids may produce first_wp_pos_in_full in increasing pos order, but ensure length correctness:
|
| 138 |
-
# print("This is first_wp_posin_full {}\n".format(first_wp_pos_in_full))
|
| 139 |
-
first_wp_pos_in_full_sorted = [None] * n_words
|
| 140 |
-
# Build first index per wid:
|
| 141 |
-
first_pos_by_wid = {}
|
| 142 |
-
for pos, wid in enumerate(word_ids):
|
| 143 |
-
if wid is not None and wid not in first_pos_by_wid:
|
| 144 |
-
first_pos_by_wid[wid] = pos
|
| 145 |
-
for wid in range(n_words):
|
| 146 |
-
first_wp_pos_in_full_sorted[wid] = first_pos_by_wid[wid]
|
| 147 |
-
|
| 148 |
-
#first_wp_pos_in_full_sorted is the indices without special tokens (e.g., CLS, SEP)
|
| 149 |
-
|
| 150 |
-
# Convert those positions (which refer to tmp with specials) to positions in our final input (with extra predicate segment).
|
| 151 |
-
# In tmp: [CLS] sentence_wp [SEP]
|
| 152 |
-
# In final: [CLS] sentence_wp [SEP] predicate_wp [SEP]
|
| 153 |
-
# So for any position 'pos' inside tmp, it points to the SAME index in final, since the prefix is identical up to first [SEP].
|
| 154 |
-
word_first_wp_fullidx = first_wp_pos_in_full_sorted # list[int] length = n_words
|
| 155 |
-
|
| 156 |
-
# Labels to IDs
|
| 157 |
-
label_ids = [self.label2id[lbl] for lbl in instance.labels]
|
| 158 |
-
assert len(label_ids) == n_words
|
| 159 |
-
|
| 160 |
-
# Predicate indicator at word level (0/1)
|
| 161 |
-
indicator = [0] * n_words
|
| 162 |
-
indicator[instance.predicate_word_idx] = 1
|
| 163 |
-
|
| 164 |
-
# [0,0,0,0,0] -> [0,0,1,0,0]
|
| 165 |
-
|
| 166 |
-
# Attention mask for the full input
|
| 167 |
-
attention_mask = [1] * len(input_ids)
|
| 168 |
-
|
| 169 |
-
# Truncate if needed (rare for normal SRL sentences but keep safe)
|
| 170 |
-
if len(input_ids) > self.max_length:
|
| 171 |
-
# We only truncate the predicate side if absolutely necessary; for simplicity, just clip tail.
|
| 172 |
-
input_ids = input_ids[:self.max_length]
|
| 173 |
-
ttids = ttids[:self.max_length]
|
| 174 |
-
attention_mask = attention_mask[:self.max_length]
|
| 175 |
-
# NOTE: word_first_wp_fullidx could reference beyond max_length in pathological cases.
|
| 176 |
-
max_pos = self.max_length - 1
|
| 177 |
-
word_first_wp_fullidx = [min(p, max_pos) for p in word_first_wp_fullidx]
|
| 178 |
-
|
| 179 |
-
if self.debug_print:
|
| 180 |
-
toks_debug = self.tokenizer.convert_ids_to_tokens(input_ids, skip_special_tokens=False)
|
| 181 |
-
print("[DeBug idx = {}]".format(idx)+" ".join(toks_debug))
|
| 182 |
-
|
| 183 |
-
return {
|
| 184 |
-
"input_ids": torch.tensor(input_ids, dtype=torch.long),
|
| 185 |
-
"token_type_ids": torch.tensor(ttids, dtype=torch.long),
|
| 186 |
-
"attention_mask": torch.tensor(attention_mask, dtype=torch.long),
|
| 187 |
-
"word_first_wp_fullidx": torch.tensor(word_first_wp_fullidx, dtype=torch.long), # [n_words]
|
| 188 |
-
"labels": torch.tensor(label_ids, dtype=torch.long), # [n_words]
|
| 189 |
-
"indicator": torch.tensor(indicator, dtype=torch.long), # [n_words]
|
| 190 |
-
"sent_len": torch.tensor(len(words), dtype=torch.long),
|
| 191 |
-
"pred_word_idx": torch.tensor(instance.predicate_word_idx, dtype=torch.long)
|
| 192 |
-
}
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
def srl_collate(batch: List[Dict], pad_token_id: int, pad_label_id: int = -100):
|
| 196 |
-
"""
|
| 197 |
-
Pads full BERT inputs to same length; also pads word-level tensors to max sentence length.
|
| 198 |
-
Returns tensors ready for the model.
|
| 199 |
-
"""
|
| 200 |
-
B = len(batch)
|
| 201 |
-
# Full sequence padding
|
| 202 |
-
max_L = max(item["input_ids"].size(0) for item in batch)
|
| 203 |
-
# print("This is B {}, max_L {}".format(B,max_L))
|
| 204 |
-
#make tensor B rows and Max_L columns
|
| 205 |
-
input_ids = torch.full((B, max_L), pad_token_id, dtype=torch.long)
|
| 206 |
-
token_type_ids = torch.zeros((B, max_L), dtype=torch.long)
|
| 207 |
-
attention_mask = torch.zeros((B, max_L), dtype=torch.long)
|
| 208 |
-
|
| 209 |
-
# Word-level padding
|
| 210 |
-
max_n = max(int(item["sent_len"]) for item in batch)
|
| 211 |
-
word_first_wp_fullidx = torch.full((B, max_n), -1, dtype=torch.long)
|
| 212 |
-
labels = torch.full((B, max_n), pad_label_id, dtype=torch.long)
|
| 213 |
-
indicator = torch.zeros((B, max_n), dtype=torch.long)
|
| 214 |
-
sent_lens = torch.zeros((B,), dtype=torch.long)
|
| 215 |
-
pred_word_idx = torch.zeros((B,), dtype=torch.long)
|
| 216 |
-
sentence_mask = torch.zeros((B, max_n), dtype=torch.bool)
|
| 217 |
-
|
| 218 |
-
for i, item in enumerate(batch):
|
| 219 |
-
# print("This is item {}".format(item))
|
| 220 |
-
L = item["input_ids"].size(0)
|
| 221 |
-
input_ids[i, :L] = item["input_ids"]
|
| 222 |
-
token_type_ids[i, :L] = item["token_type_ids"]
|
| 223 |
-
attention_mask[i, :L] = item["attention_mask"]
|
| 224 |
-
|
| 225 |
-
n = int(item["sent_len"])
|
| 226 |
-
word_first_wp_fullidx[i, :n] = item["word_first_wp_fullidx"]
|
| 227 |
-
labels[i, :n] = item["labels"]
|
| 228 |
-
indicator[i, :n] = item["indicator"]
|
| 229 |
-
sent_lens[i] = n
|
| 230 |
-
pred_word_idx[i] = item["pred_word_idx"]
|
| 231 |
-
sentence_mask[i, :n] = True
|
| 232 |
-
|
| 233 |
-
return {
|
| 234 |
-
"input_ids": input_ids,
|
| 235 |
-
"token_type_ids": token_type_ids,
|
| 236 |
-
"attention_mask": attention_mask,
|
| 237 |
-
"word_first_wp_fullidx": word_first_wp_fullidx, # [B, max_n] (full-seq positions; -1 for pad)
|
| 238 |
-
"sentence_mask": sentence_mask, # [B, max_n] (bool mask for valid words)
|
| 239 |
-
"labels": labels, # [B, max_n] (pad_label_id for pad)
|
| 240 |
-
"indicator": indicator, # [B, max_n] 0/1
|
| 241 |
-
"sent_lens": sent_lens, # [B]
|
| 242 |
-
"pred_word_idx": pred_word_idx # [B]
|
| 243 |
-
}
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
def data_processing_for_loader(train_dev_test: List[SRLSample], train_sample: List[SRLSample], dev_sample: List[SRLSample], test_sample: List[SRLSample], tokenizer):
|
| 247 |
-
|
| 248 |
-
'''
|
| 249 |
-
train_dev_test is an appended list of Train/Dev/Test SRLSamples
|
| 250 |
-
train_sample is a list of SRLSample
|
| 251 |
-
dev_sample is a list of SRLSample
|
| 252 |
-
test_sample is a list of SRLSample
|
| 253 |
-
'''
|
| 254 |
-
|
| 255 |
-
label2id = {}
|
| 256 |
-
for s in train_dev_test:
|
| 257 |
-
for l in s.labels:
|
| 258 |
-
label2id.setdefault(l, len(label2id))
|
| 259 |
-
id2label = {v: k for k, v in label2id.items()}
|
| 260 |
-
|
| 261 |
-
#train before loader
|
| 262 |
-
train_bf_loader = SRLDataset(train_sample, tokenizer, label2id, max_length = 128, debug_print = False)
|
| 263 |
-
dev_bf_loader = SRLDataset(dev_sample, tokenizer, label2id, max_length = 128, debug_print = False)
|
| 264 |
-
test_bf_loader = SRLDataset(test_sample, tokenizer, label2id, max_length = 128, debug_print = False)
|
| 265 |
-
|
| 266 |
-
return train_bf_loader, dev_bf_loader, test_bf_loader, label2id, id2label
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|