-
Notifications
You must be signed in to change notification settings - Fork 910
/
iit.py
666 lines (569 loc) · 23.2 KB
/
iit.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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
import numpy as np
import random
import torch
from utils import randvec
__author__ = "Atticus Geiger"
__version__ = "CS224u, Stanford, Spring 2023"
def get_IIT_equality_dataset_both(embed_dim, size):
train_dataset = IIT_PremackDatasetBoth(
embed_dim=embed_dim,
size=size)
X_base_train, X_sources_train, y_base_train, y_IIT_train, interventions = train_dataset.create()
X_base_train = torch.tensor(X_base_train)
X_sources_train = [torch.tensor(X_source_train) for X_source_train in X_sources_train]
y_base_train = torch.tensor(y_base_train)
y_IIT_train = torch.tensor(y_IIT_train)
interventions = torch.tensor(interventions)
return X_base_train, X_sources_train, y_base_train, y_IIT_train, interventions
def get_IIT_equality_dataset(variable, embed_dim, size):
class_size = size/2
train_dataset = IIT_PremackDataset(
variable,
embed_dim=embed_dim,
n_pos=class_size,
n_neg=class_size)
X_base_train, X_sources_train, y_base_train, y_IIT_train, interventions = train_dataset.create()
X_base_train = torch.tensor(X_base_train)
X_sources_train = [torch.tensor(X_source_train) for X_source_train in X_sources_train]
y_base_train = torch.tensor(y_base_train)
y_IIT_train = torch.tensor(y_IIT_train)
interventions = torch.tensor(interventions)
return X_base_train, X_sources_train, y_base_train, y_IIT_train, interventions
def get_equality_dataset(embed_dim, size):
class_size = size/2
train_dataset = PremackDataset(
embed_dim=embed_dim,
n_pos=class_size,
n_neg=class_size)
X_train, y_train = train_dataset.create()
test_dataset = PremackDataset(
embed_dim=embed_dim,
n_pos=class_size,
n_neg=class_size)
X_test, y_test = test_dataset.create()
train_dataset.test_disjoint(test_dataset)
X_train = torch.tensor(X_train)
X_test = torch.tensor(X_test)
return X_train, X_test, y_train, y_test, test_dataset
class EqualityDataset:
POS_LABEL = 1
NEG_LABEL = 0
def __init__(self, embed_dim=50, n_pos=500, n_neg=500, flatten=True):
"""Creates simple equality datasets, which are basically lists
of `((vec1, vec2), label)` instances, where `label == POS_LABEL`
if `vec1 == vec2`, else `label == NEG_LABEL`. With `flatten=True`,
the instances become `(vec1;vec2, label)`.
Parameters
----------
embed_dim : int
Sets the dimensionality of the individual component vectors.
n_pos : int
n_neg : int
flatten : bool
If False, instances are of the form ((vec1, vec2), label).
If True, vec1 and vec2 are concatenated, creating instances
(x, label) where len(x) == embed_dim*2.
Usage
-----
dataset = EqualityDataset()
X, y = dataset.create()
Attributes
----------
embed_dim : int
n_pos : int
n_neg : int
flatten : bool
"""
self.embed_dim = embed_dim
self.n_pos = n_pos
self.n_neg = n_neg
self.flatten = flatten
def create(self):
"""Main interface
Attributes
----------
data : list
Shuffled version of the raw instances, ignoring `self.flatten`.
Thus, these are all of the form `((vec1, vec2), label)`
X : np.array
The dimensionality depends on `self.flatten`. If it is
False, then `X.shape == (n_pos+n_neg, 2, embed_dim)`. If it
is True, then `X.shape == (n_pos+n_neg, embed_dim*2)`.
y : list
Containing `POS_LABEL` and `NEG_LABEL`. Length: n_pos+n_neg
Returns
-------
self.X, self.y
"""
self.data = []
self.data += self._create_pos()
self.data += self._create_neg()
random.shuffle(self.data)
data = self.data.copy()
if self.flatten:
data = [(np.concatenate(x), label) for x, label in data]
X, y = zip(*data)
self.X = np.array(X)
self.y = y
return self.X, self.y
def test_disjoint(self, other_dataset):
these_vecs = {tuple(x) for pair, label in self.data for x in pair}
other_vecs = {tuple(x) for pair, label in other_dataset.data for x in pair}
shared = these_vecs & other_vecs
assert len(shared) == 0, \
f"This dataset and the other dataset shared {len(shared)} word-level reps."
def _create_pos(self):
data = []
for _ in range(self.n_pos):
vec = randvec(self.embed_dim)
rep = (vec, vec)
data.append((rep, self.POS_LABEL))
return data
def _create_neg(self):
data = []
for _ in range(self.n_neg):
vec1 = randvec(self.embed_dim)
vec2 = vec1.copy()
while np.array_equal(vec1, vec2):
vec2 = randvec(self.embed_dim)
rep = (vec1, vec2)
data.append((rep, self.NEG_LABEL))
return data
class PremackDataset:
POS_LABEL = 1
NEG_LABEL = 0
def __init__(self, embed_dim=50, n_pos=500, n_neg=500,
flatten_root=True, flatten_leaves=True, intermediate=False):
"""Creates Premack datasets. Conceptually, the instances are
(((a, b), (c, d)), label)
where `label == POS_LABEL` if (a == b) == (c == d), else
`label == NEG_LABEL`. With `flatten_leaves=True`, these become
((a;b, c;d), label)
and with `flatten_root=True`, these become
(a;b;c;d, label)
and `flatten_root=True` means that `flatten_leaves=True`, since
we can't flatten the roof without flattening the leaves.
Parameters
----------
embed_dim : int
Sets the dimensionality of the individual component vectors.
n_pos : int
n_neg : int
flatten_root : bool
flatten_leaves : bool
Usage
-----
dataset = EqualityDataset()
X, y = dataset.create()
Attributes
----------
embed_dim : int
n_pos : int
n_neg : int
flatten_root : bool
flatten_leaves : bool
n_same_same : n_pos / 2
n_diff_diff : n_pos / 2
n_same_diff : n_neg / 2
n_diff_same : n_neg / 2
Raises
------
ValueError
If `n_pos` or `n_neg` is not even, since this means we
can't get an even distribtion of the two sub-types of
each of those classes while also staying faithful to
user's expected number of examples for each class.
"""
self.embed_dim = embed_dim
self.n_pos = n_pos
self.n_neg = n_neg
for n, v in ((n_pos, 'n_pos'), (n_neg, 'n_neg')):
if n % 2 != 0:
raise ValueError(
f"The value of {v} must be even to ensure a balanced "
f"split across its two sub-types of the {v} class.")
self.n_same_same = int(n_pos / 2)
self.n_diff_diff = int(n_pos / 2)
self.n_same_diff = int(n_neg / 2)
self.n_diff_same = int(n_neg / 2)
self.flatten_root = flatten_root
self.flatten_leaves = flatten_leaves
self.intermediate = intermediate
def create(self):
"""Main interface
Attributes
----------
data : list
Shuffled version of the raw instances, ignoring
`self.flatten_root` and `self.flatten_leaves`.
Thus, these are all of the form `(((a, b), (c, d)), label)`
X : np.array
The dimensionality depends on `self.flatten_root` and
`self.flatten_leaves`.
If both are False, then
`X.shape == (n_pos+n_neg, 2, 2, embed_dim)`
If `self.flatten_root`, then
`X.shape == (n_pos+n_neg, embed_dim*4)`
If only `self.flatten_leaves`, then
`X.shape == (n_pos+n_neg, 2, embed_dim*2)`
y : list
Containing `POS_LABEL` and `NEG_LABEL`. Length: n_pos+n_neg
Returns
-------
self.X, self.y
"""
self.data = []
self.data += self._create_same_same()
self.data += self._create_diff_diff()
self.data += self._create_same_diff()
self.data += self._create_diff_same()
random.shuffle(self.data)
data = self.data.copy()
if self.flatten_root or self.flatten_leaves:
data = [((np.concatenate(x1), np.concatenate(x2)), label)
for (x1, x2), label in data]
if self.flatten_root:
data = [(np.concatenate(x), label) for x, label in data]
X, y = zip(*data)
self.X = np.array(X)
self.y = y
return self.X, self.y
def test_disjoint(self, other_dataset):
these_vecs = {tuple(x) for root_pair, label in self.data
for pair in root_pair for x in pair}
other_vecs = {tuple(x) for root_pair, label in other_dataset.data
for pair in root_pair for x in pair}
shared = these_vecs & other_vecs
assert len(shared) == 0, \
f"This dataset and the other dataset shared {len(shared)} word-level reps."
def _create_same_same(self):
data = []
for _ in range(self.n_same_same):
left = self._create_same_pair()
right = self._create_same_pair()
rep = (left, right)
data.append((rep, self.POS_LABEL))
return data
def _create_diff_diff(self):
data = []
for _ in range(self.n_diff_diff):
left = self._create_diff_pair()
right = self._create_diff_pair()
rep = (left, right)
data.append((rep, self.POS_LABEL))
return data
def _create_same_diff(self):
data = []
for _ in range(self.n_same_diff):
left = self._create_same_pair()
right = self._create_diff_pair()
rep = (left, right)
data.append((rep, self.NEG_LABEL))
return data
def _create_diff_same(self):
data = []
for _ in range(self.n_diff_same):
left = self._create_diff_pair()
right = self._create_same_pair()
rep = (left, right)
data.append((rep, self.NEG_LABEL))
return data
def _create_same_pair(self):
vec = randvec(self.embed_dim)
return (vec, vec)
def _create_diff_pair(self):
vec1 = randvec(self.embed_dim)
vec2 = randvec(self.embed_dim)
assert not np.array_equal(vec1, vec2)
return (vec1, vec2)
class PremackDatasetLeafFlattened(PremackDataset):
def __init__(self, embed_dim=50, n_pos=500, n_neg=500):
super().__init__(
embed_dim=embed_dim,
n_pos=n_pos,
n_neg=n_neg,
flatten_leaves=True,
flatten_root=False,
intermediate=False)
class IIT_PremackDataset:
V1 = 0
V2 = 1
POS_LABEL = 1
NEG_LABEL = 0
def __init__(self, variable, embed_dim=50, n_pos=500, n_neg=500,
flatten_root=True, flatten_leaves=True, intermediate=False):
self.variable = variable
self.embed_dim = embed_dim
self.n_pos = n_pos
self.n_neg = n_neg
for n, v in ((n_pos, 'n_pos'), (n_neg, 'n_neg')):
if n % 2 != 0:
raise ValueError(
f"The value of {v} must be even to ensure a balanced "
f"split across its two sub-types of the {v} class.")
self.n_same_same_to_same = int(n_pos / 4)
self.n_diff_diff_to_same = int(n_neg / 4)
self.n_same_diff_to_same = int(n_neg / 4)
self.n_diff_same_to_same = int(n_neg / 4)
self.n_same_same_to_diff = int(n_neg / 4)
self.n_diff_diff_to_diff = int(n_neg / 4)
self.n_same_diff_to_diff = int(n_neg / 4)
self.n_diff_same_to_diff = int(n_neg / 4)
self.flatten_root = flatten_root
self.flatten_leaves = flatten_leaves
self.intermediate = intermediate
def create(self):
self.data = []
self.data += self._create_same_same_to_same()
self.data += self._create_diff_diff_to_same()
self.data += self._create_same_diff_to_same()
self.data += self._create_diff_same_to_same()
self.data += self._create_same_same_to_diff()
self.data += self._create_diff_diff_to_diff()
self.data += self._create_same_diff_to_diff()
self.data += self._create_diff_same_to_diff()
random.shuffle(self.data)
data = self.data.copy()
if self.flatten_root or self.flatten_leaves:
data = [((np.concatenate(x1), np.concatenate(x2)),(np.concatenate(x3), np.concatenate(x4)), base_label, IIT_label, intervention)
for (x1, x2,x3,x4), base_label, IIT_label, intervention in data]
if self.flatten_root:
data = [(np.concatenate(base), np.concatenate(source), label, IIT_label, intervention)
for base, source, label, IIT_label, intervention in data]
base, source, y, IIT_y, interventions = zip(*data)
self.base = np.array(base)
self.source = np.array(source)
self.y = np.array(y)
self.IIT_y = np.array(IIT_y)
self.interventions = np.array(interventions)
self.sources = list()
self.sources.append(self.source)
return self.base, self.sources, self.y, self.IIT_y, self.interventions
def _create_same_same_to_same(self):
data = []
for _ in range(self.n_same_same_to_same):
base_left = self._create_same_pair()
base_right = self._create_same_pair()
base_label = self.POS_LABEL
if self.variable == "V1":
source_left = self._create_same_pair()
source_right = self._create_random_pair()
IIT_label = self.POS_LABEL
intervention = self.V1
if self.variable == "V2":
source_left = self._create_random_pair()
source_right = self._create_same_pair()
intervention = self.V2
IIT_label = self.POS_LABEL
rep = (base_left, base_right, source_left,source_right)
data.append((rep, base_label, IIT_label, intervention))
return data
def _create_diff_diff_to_same(self):
data = []
for _ in range(self.n_diff_diff_to_same):
base_left = self._create_diff_pair()
base_right = self._create_diff_pair()
base_label = self.POS_LABEL
if self.variable == "V1":
source_left = self._create_same_pair()
source_right = self._create_random_pair()
IIT_label = self.NEG_LABEL
intervention = self.V1
if self.variable == "V2":
source_left = self._create_random_pair()
source_right = self._create_same_pair()
IIT_label = self.NEG_LABEL
intervention = self.V2
rep = (base_left, base_right, source_left,source_right)
data.append((rep, base_label, IIT_label, intervention))
return data
def _create_same_diff_to_same(self):
data = []
for _ in range(self.n_same_diff_to_same):
base_left = self._create_same_pair()
base_right = self._create_diff_pair()
base_label = self.NEG_LABEL
if self.variable == "V1":
source_left = self._create_same_pair()
source_right = self._create_random_pair()
IIT_label = self.NEG_LABEL
intervention = self.V1
if self.variable == "V2":
source_left = self._create_random_pair()
source_right = self._create_same_pair()
IIT_label = self.POS_LABEL
intervention = self.V2
rep = (base_left, base_right, source_left,source_right)
data.append((rep, base_label, IIT_label, intervention))
return data
def _create_diff_same_to_same(self):
data = []
for _ in range(self.n_diff_same_to_same):
base_left = self._create_diff_pair()
base_right = self._create_same_pair()
base_label = self.NEG_LABEL
if self.variable == "V1":
source_left = self._create_same_pair()
source_right = self._create_random_pair()
IIT_label = self.POS_LABEL
intervention = self.V1
if self.variable == "V2":
source_left = self._create_random_pair()
source_right = self._create_same_pair()
IIT_label = self.NEG_LABEL
intervention = self.V2
rep = (base_left, base_right, source_left,source_right)
data.append((rep, base_label, IIT_label, intervention))
return data
def _create_same_same_to_diff(self):
data = []
for _ in range(self.n_same_same_to_diff):
base_left = self._create_same_pair()
base_right = self._create_same_pair()
base_label = self.POS_LABEL
if self.variable == "V1":
source_left = self._create_diff_pair()
source_right = self._create_random_pair()
IIT_label = self.NEG_LABEL
intervention = self.V1
if self.variable == "V2":
source_left = self._create_random_pair()
source_right = self._create_diff_pair()
IIT_label = self.NEG_LABEL
intervention = self.V2
rep = (base_left, base_right, source_left,source_right)
data.append((rep, base_label, IIT_label, intervention))
return data
def _create_diff_diff_to_diff(self):
data = []
for _ in range(self.n_diff_diff_to_diff):
base_left = self._create_diff_pair()
base_right = self._create_diff_pair()
base_label = self.POS_LABEL
if self.variable == "V1":
source_left = self._create_diff_pair()
source_right = self._create_random_pair()
IIT_label = self.POS_LABEL
intervention = self.V1
if self.variable == "V2":
source_left = self._create_random_pair()
source_right = self._create_diff_pair()
IIT_label = self.POS_LABEL
intervention = self.V2
rep = (base_left, base_right, source_left,source_right)
data.append((rep, base_label, IIT_label, intervention))
return data
def _create_same_diff_to_diff(self):
data = []
for _ in range(self.n_same_diff_to_diff):
base_left = self._create_same_pair()
base_right = self._create_diff_pair()
base_label = self.NEG_LABEL
if self.variable == "V1":
source_left = self._create_diff_pair()
source_right = self._create_random_pair()
IIT_label = self.POS_LABEL
intervention = self.V1
if self.variable == "V2":
source_left = self._create_random_pair()
source_right = self._create_diff_pair()
IIT_label = self.NEG_LABEL
intervention = self.V2
rep = (base_left, base_right, source_left,source_right)
data.append((rep, base_label, IIT_label, intervention))
return data
def _create_diff_same_to_diff(self):
data = []
for _ in range(self.n_diff_same_to_diff):
base_left = self._create_diff_pair()
base_right = self._create_same_pair()
base_label = self.NEG_LABEL
if self.variable == "V1":
source_left = self._create_diff_pair()
source_right = self._create_random_pair()
IIT_label = self.NEG_LABEL
intervention = self.V1
if self.variable == "V2":
source_left = self._create_random_pair()
source_right = self._create_diff_pair()
IIT_label = self.POS_LABEL
intervention = self.V2
rep = (base_left, base_right, source_left,source_right)
data.append((rep, base_label, IIT_label, intervention))
return data
def _create_random_pair(self):
if random.choice([True,False]):
return self._create_same_pair()
else:
return self._create_diff_pair()
def _create_same_pair(self):
vec = randvec(self.embed_dim)
return (vec, vec)
def _create_diff_pair(self):
vec1 = randvec(self.embed_dim)
vec2 = randvec(self.embed_dim)
assert not np.array_equal(vec1, vec2)
return (vec1, vec2)
class IIT_PremackDatasetBoth:
V1 = 0
V2 = 1
POS_LABEL = 1
NEG_LABEL = 0
both_coord_id = 2
def __init__(self, size= 1000, embed_dim=50, flatten_root=True, flatten_leaves=True, intermediate=False):
self.embed_dim = embed_dim
self.size= size
self.flatten_root = flatten_root
self.flatten_leaves = flatten_leaves
self.intermediate = intermediate
def create(self):
data = []
for _ in range(self.size):
rep = [self._create_random_pair() for _ in range(6)]
if (rep[0][0] == rep[0][1]).all() == (rep[1][0] == rep[1][1]).all():
base_label = self.POS_LABEL
else:
base_label = self.NEG_LABEL
if (rep[2][0] == rep[2][1]).all() == (rep[5][0] == rep[5][1]).all():
IIT_label = self.POS_LABEL
else:
IIT_label = self.NEG_LABEL
data.append((rep,base_label, IIT_label, self.both_coord_id))
random.shuffle(data)
data = data.copy()
if self.flatten_root or self.flatten_leaves:
data = [
(
(
(np.concatenate(x1), np.concatenate(x2)),
(np.concatenate(x3), np.concatenate(x4)),
(np.concatenate(x5), np.concatenate(x6))
),
base_label, IIT_label, intervention
)
for (x1, x2,x3,x4,x5,x6), base_label, IIT_label, intervention in data
]
if self.flatten_root:
data = [(np.concatenate(base), np.concatenate(source),np.concatenate(source2), label, IIT_label, intervention)
for (base, source, source2), label, IIT_label, intervention in data]
base, source, source2, y, IIT_y, interventions = zip(*data)
self.base = np.array(base)
self.source = np.array(source)
self.source2 = np.array(source2)
self.y = np.array(y)
self.IIT_y = np.array(IIT_y)
self.interventions = np.array(interventions)
return self.base, [self.source, self.source2], self.y, self.IIT_y, self.interventions
def _create_random_pair(self):
if random.choice([True,False]):
return self._create_same_pair()
else:
return self._create_diff_pair()
def _create_same_pair(self):
vec = randvec(self.embed_dim)
return (vec, vec)
def _create_diff_pair(self):
vec1 = randvec(self.embed_dim)
vec2 = randvec(self.embed_dim)
assert not np.array_equal(vec1, vec2)
return (vec1, vec2)