-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenstax_dataset.py
651 lines (528 loc) · 25.2 KB
/
openstax_dataset.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
"""Dataloading for custom learning objective dataset."""
import numpy as np
import pandas as pd
import torch
from torch.utils.data import dataset, sampler, dataloader
from sentence_transformers import SentenceTransformer
import util
FRAC_TRAIN_CLASSES = 0.8
FRAC_VAL_CLASSES = 0.1
FRAC_TEST_CLASSES = 0.1
SEED = 42
class GPT3Dataset(dataset.Dataset):
"""
Data wrapper for GPT-3 embeddings, for held-out test set.
Paralel to nWaykShotDataset
"""
_OPENSTAX_COURSES = [
'Chemistry 2e',
'University Physics Volume 1',
'University Physics Volume 2',
'University Physics Volume 3'
]
_PRINCIPLES_OF_CHEMISTRY_COURSE = 'Principles of Chemistry 3rd edition'
_CHEM31A_COURSE = 'Chem 31A'
def __init__(self, num_support, num_query, zero_shot=False, seed=SEED) -> None:
super().__init__()
self.num_support = num_support
self.num_query = num_query
self.seed = seed
# flag whether we're using learning goal embeddings
self.tam = False
# load questions from Openstax Dataset
# columns: question, learning_goal, course (all text)
# multiple learning goals per question, multiple questions per course
data = pd.concat([
util.load_openstax_course(course) for course in self._OPENSTAX_COURSES
] + [util.load_principles_of_chemistry_course(self._PRINCIPLES_OF_CHEMISTRY_COURSE)])
# data = util.load_chem31a_course()
# group data by question
# dictionary mapping from course name to dataframe of questions within this course
# columns: question (str), learning_goal (list), course (list of single str)
self.data_by_question = {
course_name: data[data['course'] == course_name].groupby('question').agg(list)
for course_name in data['course'].unique()
}
# group data by learning goal
# columns: question (list), learning_goal (str), course (list of single str)
self.data_by_learning_goal = data.groupby('learning_goal').agg(list)
learning_goal_embeddings = torch.load('learning_goal_curie_embeddings.pt')
self.learning_goal_to_embedding = dict(zip(
self.data_by_learning_goal.index, learning_goal_embeddings
))
# ignore learning goals that do not have enough training examples
# NOTE: questions under these learning goals can still appear as NEGATIVE examples, just not positive examples
self.data_by_learning_goal = self.data_by_learning_goal[
self.data_by_learning_goal['question'].apply(len) >= self.num_support + self.num_query
]
# shuffle order of learning goals for training!!
self.data_by_learning_goal = self.data_by_learning_goal.sample(frac=1., random_state=self.seed)
question_embeddings = torch.load('question_curie_embeddings.pt')
self.question_to_embedding = dict(zip(
[q for key in self.data_by_question for q in self.data_by_question[key].index], question_embeddings
))
self.zero_shot = zero_shot
# construct a random number generator
self.rng = np.random.default_rng(seed=self.seed)
def get_data_by_learning_goal(self):
return self.data_by_learning_goal
def __getitem__(self, index):
if self.zero_shot:
learning_goal = self.data_by_learning_goal.iloc[index]
query_1 = self.rng.choice(
learning_goal.question, self.num_query, replace=False
)
examples_0 = self.data_by_question[learning_goal.course[0]].drop(learning_goal.question)
query_0 = self.rng.choice(
examples_0.index,
self.num_query,
replace=False
)
learning_goals_0 = [self.rng.choice(lgs) for lgs in examples_0.loc[query_0].learning_goal.values]
learning_goals_1 = [learning_goal.name] * self.num_query
query = list(query_0) + list(query_1)
learning_goals = learning_goals_0 + learning_goals_1
labels = ([0] * self.num_query) + ([1] * self.num_query)
query = torch.stack([self.question_to_embedding[q] for q in query])
learning_goals = torch.stack([self.learning_goal_to_embedding[l] for l in learning_goals])
labels = torch.tensor(labels)
return learning_goals, query, labels
# get learning goal from index
learning_goal = self.data_by_learning_goal.iloc[index]
# select examples that match the sampled learning goal
examples_1 = learning_goal.question
support_and_query_1 = self.rng.choice(
examples_1, self.num_support + self.num_query, replace=False
)
support_1 = support_and_query_1[:self.num_support]
query_1 = support_and_query_1[self.num_support:]
# select examples that do not have this learning goal
examples_0 = self.data_by_question[learning_goal.course[0]].drop(learning_goal.question).index
support_and_query_0 = self.rng.choice(
examples_0, self.num_support + self.num_query, replace=False
)
support_0 = support_and_query_0[:self.num_support]
query_0 = support_and_query_0[self.num_support:]
support = list(support_0) + list(support_1)
query = list(query_0) + list(query_1)
labels_support = ([0] * self.num_support) + ([1] * self.num_support)
labels_query = ([0] * self.num_query) + ([1] * self.num_query)
support = torch.stack([self.question_to_embedding[q] for q in support])
query = torch.stack([self.question_to_embedding[q] for q in query])
labels_support, labels_query = torch.tensor(labels_support), torch.tensor(labels_query)
return support, labels_support, query, labels_query
def __len__(self) -> int:
return self.data_by_learning_goal.shape[0]
class GPT3TestDataset(dataset.Dataset):
"""
Dataset wrapper for GPT-3 embeddings for held-out course.
Parallel to CourseTestDataset
"""
_OPENSTAX_COURSES = [
'Chemistry 2e',
'University Physics Volume 1',
'University Physics Volume 2',
'University Physics Volume 3'
]
_PRINCIPLES_OF_CHEMISTRY_COURSE = 'Principles of Chemistry 3rd edition'
_CHEM31A_COURSE = 'Chem 31A'
def __init__(self, course_name, num_support, num_query, zero_shot=False) -> None:
super().__init__()
self.num_support = num_support
self.num_query = num_query
# load questions from Openstax Dataset
# columns: question, learning_goal, course (all text)
# multiple learning goals per question, multiple questions per course
if course_name in self._OPENSTAX_COURSES:
data = util.load_openstax_course(course_name)
elif course_name == self._PRINCIPLES_OF_CHEMISTRY_COURSE:
data = util.load_principles_of_chemistry_course(course_name)
elif course_name == self._CHEM31A_COURSE:
data = util.load_chem31a_course()
# group data by question
# columns: question (str), learning_goal (list), course (list of single str)
self.data_by_question = data.groupby('question').agg(list)
question_embeddings = torch.load('question_curie_embeddings_chem31a.pt')
self.question_to_embedding = dict(zip(
self.data_by_question.index, question_embeddings
))
# group data by learning goal
# columns: question (list), learning_goal (str), course (list of single str)
self.data_by_learning_goal = data.groupby('learning_goal').agg(list)
learning_goal_embeddings = torch.load('learning_goal_curie_embeddings_chem31a.pt')
self.learning_goal_to_embedding = dict(zip(
self.data_by_learning_goal.index, learning_goal_embeddings
))
self.data_by_learning_goal = self.data_by_learning_goal[
self.data_by_learning_goal['question'].apply(len) > 1
]
self.zero_shot = zero_shot
def __getitem__(self, question_index):
question = self.data_by_question.iloc[question_index].name
tasks = []
for i, learning_goal in enumerate(self.data_by_learning_goal.index):
if self.zero_shot:
query = [question]
support_1 = [learning_goal]
support_0 = [np.random.default_rng(seed=SEED).choice(
self.data_by_learning_goal.drop(learning_goal).index
)]
support = support_0 + support_1
labels = [int(question in self.data_by_learning_goal.loc[learning_goal].question)]
support = torch.stack([self.learning_goal_to_embedding[s] for s in support])
query = torch.stack([self.question_to_embedding[q] for q in query])
labels = torch.tensor(labels)
tasks.append(
(support, query, labels)
)
continue
# select examples that match the sampled learning goal
examples_1 = self.data_by_learning_goal.loc[learning_goal].question
examples_1_minus_q = [q for q in examples_1 if q != question]
support_1 = np.random.default_rng(seed=SEED).choice(examples_1_minus_q, self.num_support)
# select examples that do not have this learning goal
examples_0 = self.data_by_question.drop(examples_1).index
support_0 = np.random.default_rng(seed=SEED).choice(examples_0, self.num_support)
support = list(support_0) + list(support_1)
query = [question]
labels_support = ([0] * self.num_support) + ([1] * self.num_support)
labels_query = [int(question in examples_1)]
support = torch.stack([self.question_to_embedding[s] for s in support])
query = torch.stack([self.question_to_embedding[q] for q in query])
labels_support, labels_query = torch.tensor(labels_support), torch.tensor(labels_query)
tasks.append(
(support, labels_support, query, labels_query)
)
return tasks
def __len__(self) -> int:
return self.data_by_question.shape[0]
class CourseTestDataset(dataset.Dataset):
"""
Dataset for testing a model on tagging a full course, given the course name.
In this setting, each question consists of a number of tasks equal to
the number of learning objectives in the course. A question
is labeled with all learning objectives to which the model assigns a positive
prediction score.
"""
_OPENSTAX_COURSES = [
'Chemistry 2e',
'University Physics Volume 1',
'University Physics Volume 2',
'University Physics Volume 3'
]
_PRINCIPLES_OF_CHEMISTRY_COURSE = 'Principles of Chemistry 3rd edition'
_CHEM31A_COURSE = 'Chem 31A'
def __init__(self, course_name, num_support, num_query, tokenizer, max_length=128, task_embedding_model=None) -> None:
super().__init__()
self.num_support = num_support
self.num_query = num_query
self.tokenizer = tokenizer
self.max_length = max_length
# flag whether we're using learning goal embeddings
self.tam = False
# load questions from Openstax Dataset
# columns: question, learning_goal, course (all text)
# multiple learning goals per question, multiple questions per course
if course_name in self._OPENSTAX_COURSES:
data = util.load_openstax_course(course_name)
elif course_name == self._PRINCIPLES_OF_CHEMISTRY_COURSE:
data = util.load_principles_of_chemistry_course(course_name)
elif course_name == self._CHEM31A_COURSE:
data = util.load_chem31a_course()
# group data by question
# columns: question (str), learning_goal (list), course (list of single str)
self.data_by_question = data.groupby('question').agg(list)
# group data by learning goal
# columns: question (list), learning_goal (str), course (list of single str)
self.data_by_learning_goal = data.groupby('learning_goal').agg(list)
self.data_by_learning_goal = self.data_by_learning_goal[
self.data_by_learning_goal['question'].apply(len) > 1
]
# encode learning goals as task embeddings
self.tam = False
if task_embedding_model is not None:
with torch.no_grad():
self.learning_goal_embeddings = task_embedding_model.encode(
self.data_by_learning_goal.index.values
)
self.tam = True
def _tokenize(self, x):
return self.tokenizer(
x,
return_tensors='pt',
max_length=self.max_length,
add_special_tokens=True,
padding='max_length',
truncation=True,
return_attention_mask=True
)
def __getitem__(self, question_index):
question = self.data_by_question.iloc[question_index].name
tasks = []
for i, learning_goal in enumerate(self.data_by_learning_goal.index):
# select examples that match the sampled learning goal
examples_1 = self.data_by_learning_goal.loc[learning_goal].question
examples_1_minus_q = [q for q in examples_1 if q != question]
support_1 = np.random.default_rng(seed=SEED).choice(examples_1_minus_q, self.num_support)
# select examples that do not have this learning goal
examples_0 = self.data_by_question.drop(examples_1).index
support_0 = np.random.default_rng(seed=SEED).choice(examples_0, self.num_support)
support = list(support_0) + list(support_1)
query = [question]
labels_support = ([0] * self.num_support) + ([1] * self.num_support)
labels_query = [int(question in examples_1)]
if self.tokenizer:
support, query = self._tokenize(support), self._tokenize(query)
# add in task embeddings
if self.tam:
support.update({
'task_embeds': torch.tensor(self.learning_goal_embeddings[i]).unsqueeze(0).repeat(2 * self.num_support, 1).unsqueeze(1)
})
query.update({
'task_embeds': torch.tensor(self.learning_goal_embeddings[i]).unsqueeze(0).repeat(1, 1).unsqueeze(1)
})
labels_support, labels_query = torch.tensor(labels_support), torch.tensor(labels_query)
tasks.append(
(support, labels_support, query, labels_query)
)
return tasks
def __len__(self) -> int:
return self.data_by_question.shape[0]
class nWaykShotDataset(dataset.Dataset):
"""
Dataset for n-way k-shot classification of questions with learning objectives.
Used to train and evaluate prototypical network.
"""
_OPENSTAX_COURSES = [
'Chemistry 2e',
'University Physics Volume 1',
'University Physics Volume 2',
'University Physics Volume 3'
]
_PRINCIPLES_OF_CHEMISTRY_COURSE = 'Principles of Chemistry 3rd edition'
def __init__(
self,
num_support,
num_query,
tokenizer,
task_embedding_model=None,
max_length=256,
balanced=True,
seed=SEED
) -> None:
super().__init__()
self.num_support = num_support
self.num_query = num_query
self.tokenizer = tokenizer
self.max_length = max_length
self.seed = seed
self.balanced = balanced
# flag whether we're using learning goal embeddings
self.tam = False
# load questions from Openstax Dataset
# columns: question, learning_goal, course (all text)
# multiple learning goals per question, multiple questions per course
data = pd.concat([
util.load_openstax_course(course) for course in self._OPENSTAX_COURSES
] + [util.load_principles_of_chemistry_course(self._PRINCIPLES_OF_CHEMISTRY_COURSE)])
# group data by question
# dictionary mapping from course name to dataframe of questions within this course
# columns: question (str), learning_goal (list), course (list of single str)
self.data_by_question = {
course_name: data[data['course'] == course_name].groupby('question').agg(list)
for course_name in data['course'].unique()
}
# group data by learning goal
# columns: question (list), learning_goal (str), course (list of single str)
self.data_by_learning_goal = data.groupby('learning_goal').agg(list)
# ignore learning goals that do not have enough training examples
# NOTE: questions under these learning goals can still appear as NEGATIVE examples, just not positive examples
self.data_by_learning_goal = self.data_by_learning_goal[
self.data_by_learning_goal['question'].apply(len) >= self.num_support + self.num_query
]
# shuffle order of learning goals for training!!
self.data_by_learning_goal = self.data_by_learning_goal.sample(frac=1., random_state=self.seed)
# encode learning goals as task embeddings
if task_embedding_model is not None:
with torch.no_grad():
self.learning_goal_embeddings = task_embedding_model.encode(
self.data_by_learning_goal.index.values
)
self.tam = True
# construct a random number generator
self.rng = np.random.default_rng(seed=self.seed)
def _tokenize(self, x):
return self.tokenizer(
x,
return_tensors='pt',
max_length=self.max_length,
add_special_tokens=True,
padding='max_length',
truncation=True,
return_attention_mask=True
)
def get_data_by_learning_goal(self):
return self.data_by_learning_goal
def __getitem__(self, index):
if not self.balanced:
# get learning goal from index
learning_goal = self.data_by_learning_goal.iloc[index]
# select examples that match the sampled learning goal
examples_1 = learning_goal.question
support_and_query_1 = self.rng.choice(
examples_1, self.num_support, replace=False
)
support_1 = support_and_query_1[:self.num_support]
query_1 = support_and_query_1[self.num_support:]
# select examples that do not have this learning goal
examples_0 = self.data_by_question[learning_goal.course[0]].drop(learning_goal.question).index
support_and_query_0 = self.rng.choice(
examples_0, self.num_support + self.num_query, replace=False
)
support_0 = support_and_query_0[:self.num_support]
query_0 = support_and_query_0[self.num_support:]
support = list(support_0) + list(support_1)
# query = list(self.rng.choice(
# self.data_by_question[learning_goal.course[0]].drop(support).index, self.num_query, replace=False
# ))
query = list(query_0) + list(query_1)
labels_support = ([0] * self.num_support) + ([1] * self.num_support)
# labels_query = [int(q in learning_goal.question) for q in query]
labels_query = ([0] * self.num_query) + ([1] * self.num_query)
if self.tokenizer:
support, query = self._tokenize(support), self._tokenize(query)
# add in task embeddings
if self.tam:
support.update({
'task_embeds': torch.tensor(self.learning_goal_embeddings[index]).unsqueeze(0).repeat(2 * self.num_support, 1).unsqueeze(1)
})
query.update({
'task_embeds': torch.tensor(self.learning_goal_embeddings[index]).unsqueeze(0).repeat(2 * self.num_query, 1).unsqueeze(1)
})
labels_support, labels_query = torch.tensor(labels_support), torch.tensor(labels_query)
return support, labels_support, query, labels_query
else:
# get learning goal from index
learning_goal = self.data_by_learning_goal.iloc[index]
# select examples that match the sampled learning goal
examples_1 = learning_goal.question
support_and_query_1 = self.rng.choice(
examples_1, self.num_support + self.num_query, replace=False
)
support_1 = support_and_query_1[:self.num_support]
query_1 = support_and_query_1[self.num_support:]
# select examples that do not have this learning goal
examples_0 = self.data_by_question[learning_goal.course[0]].drop(learning_goal.question).index
support_and_query_0 = self.rng.choice(
examples_0, self.num_support + self.num_query, replace=False
)
support_0 = support_and_query_0[:self.num_support]
query_0 = support_and_query_0[self.num_support:]
support = list(support_0) + list(support_1)
query = list(query_0) + list(query_1)
labels_support = ([0] * self.num_support) + ([1] * self.num_support)
labels_query = ([0] * self.num_query) + ([1] * self.num_query)
if self.tokenizer:
support, query = self._tokenize(support), self._tokenize(query)
# add in task embeddings
if self.tam:
support.update({
'task_embeds': torch.tensor(self.learning_goal_embeddings[index]).unsqueeze(0).repeat(2 * self.num_support, 1).unsqueeze(1)
})
query.update({
'task_embeds': torch.tensor(self.learning_goal_embeddings[index]).unsqueeze(0).repeat(2 * self.num_query, 1).unsqueeze(1)
})
labels_support, labels_query = torch.tensor(labels_support), torch.tensor(labels_query)
return support, labels_support, query, labels_query
def __len__(self) -> int:
return self.data_by_learning_goal.shape[0]
class nWaykShotSampler(sampler.Sampler):
def __init__(self, split_idx, num_tasks, seed=SEED) -> None:
super().__init__(None)
self._num_tasks = num_tasks
self._indices = split_idx
self.rng = np.random.default_rng(seed=seed)
def __iter__(self):
if self._num_tasks is None:
return (i for i in self._indices)
else:
return (
self.rng.choice(self._indices, replace=False)
for _ in range(self._num_tasks)
)
def __len__(self):
if self._num_tasks is None:
return len(self._indices)
else:
return self._num_tasks
class ContrastiveSampler(sampler.Sampler):
def __init__(self, dataset : nWaykShotDataset, split_idx, num_tasks, seed=SEED) -> None:
super().__init__(dataset)
self._num_tasks = num_tasks
self._indices = split_idx
self.rng = np.random.default_rng(seed=seed)
self.data_by_learning_goal = dataset.get_data_by_learning_goal().reset_index()
def _sample_learning_goal_index(self, index):
lg = self.data_by_learning_goal.iloc[index]
safe_lgs = self.data_by_learning_goal[
self.data_by_learning_goal['question'].apply(lambda l: all([q not in lg.question for q in l]))
]
return self.rng.choice(safe_lgs.index)
def __iter__(self):
return (
(i, self._sample_learning_goal_index(i))
for i in range(self.rng.choice(self.data_by_learning_goal.index, size=self.num_tasks, replace=False))
)
def __len__(self):
return self._num_tasks
def identity(x):
return x
def get_nway_kshot_dataloader(
split,
batch_size,
num_support,
num_query,
num_tasks_per_epoch,
tokenizer,
task_embedding_model_type=None, # SBERT model to encode tasks
num_workers=8,
max_length=128,
sample_by_learning_goal=False,
balanced=True,
seed=SEED
):
if task_embedding_model_type is not None:
task_embedding_model = SentenceTransformer(task_embedding_model_type)
else:
task_embedding_model = None
dataset = nWaykShotDataset(
num_support,
num_query,
tokenizer,
task_embedding_model=task_embedding_model,
max_length=max_length,
balanced=balanced,
seed=seed
)
num_train_classes = int(len(dataset) * FRAC_TRAIN_CLASSES)
num_val_classes = int(len(dataset) * FRAC_VAL_CLASSES)
num_test_classes = int(len(dataset) * FRAC_TEST_CLASSES)
if split == 'train':
split_idxs = range(num_train_classes)
elif split == 'val':
split_idxs = range(num_train_classes, num_train_classes + num_val_classes)
else:
split_idxs = range(num_train_classes + num_val_classes, num_train_classes + num_val_classes + num_test_classes)
if sample_by_learning_goal:
sampler = ContrastiveSampler(dataset, split_idxs, num_tasks_per_epoch, seed)
else:
sampler = nWaykShotSampler(split_idxs, num_tasks_per_epoch, seed)
return dataloader.DataLoader(
dataset=dataset,
batch_size=batch_size,
sampler=sampler,
num_workers=num_workers,
collate_fn=identity,
pin_memory=torch.cuda.is_available(),
drop_last=True
)