TheFireHacker commited on
Commit
b465019
·
verified ·
1 Parent(s): 069f4a6

Add contrastive binding v1 + v2 (parquet), generators, dataset card

Browse files
README.md CHANGED
@@ -1,3 +1,100 @@
1
  ---
2
- license: cc-by-4.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ task_categories:
6
+ - text-generation
7
+ tags:
8
+ - synthetic
9
+ - entity-binding
10
+ - coreference
11
+ - minimal-pairs
12
+ - winogrande-style
13
+ - pretraining
14
+ pretty_name: BubblSpace Contrastive Binding
15
+ size_categories:
16
+ - 1M<n<10M
17
+ configs:
18
+ - config_name: v1
19
+ data_files:
20
+ - split: train
21
+ path: v1/*.parquet
22
+ - config_name: v2
23
+ data_files:
24
+ - split: train
25
+ path: v2/*.parquet
26
  ---
27
+
28
+ # BubblSpace Contrastive Binding
29
+
30
+ Template-generated English documents that teach **entity–attribute binding**: keeping track of *which* entity a property, role, feeling or possession belongs to. Every document is generated by a Python script (no LLM), so every example is correct by construction.
31
+
32
+ Built for [BubblSpace MoE-0.9B-A0.2B](https://huggingface.co/TheFireHacker/bubblspace-moe0.9b-a0.2b), a 915M-parameter (211M active) mixture-of-experts model trained from scratch. Code and recipes: [github.com/thefirehacker/bubblspace-MoE-0.9B-A0.2B](https://github.com/thefirehacker/bubblspace-MoE-0.9B-A0.2B).
33
+
34
+ ```python
35
+ from datasets import load_dataset
36
+ v2 = load_dataset("TheFireHacker/bubblspace-contrastive-binding", "v2", split="train")
37
+ ```
38
+
39
+ ## Why
40
+
41
+ After Phase 1 pretraining (10B tokens of FineWeb-Edu), the model was fluent but bound attributes to the wrong entity. WinoGrande stayed at chance (~51%), and on our own WinoGrande-style probe it scored 25/100, with three categories at 0%. The probe uses minimal pairs where only the entity changes, and a case counts only if the model's preferred completion flips with it:
42
+
43
+ ```
44
+ The suitcase would not fit in the car trunk because the trunk was … → " too small."
45
+ The suitcase would not fit in the car trunk because the suitcase was … → " too big."
46
+ ```
47
+
48
+ This dataset puts that skill directly into pretraining data.
49
+
50
+ ## Versions
51
+
52
+ | Config | Docs | Tokens* | What it contains | Used in |
53
+ |---|---|---|---|---|
54
+ | **v1** | 2,089,904 | 61.9M | One causal frame family ("A did X to B because B was …"), in a few surface forms: plain statements, Q&A ("Which one was …? Answer: …"), and explanations with a contrasting negative ("Nobody thought A was …") | Phase 2, Stage 2A (~2.4 passes) |
55
+ | **v2** | 3,635,229 | 133.5M | **15 sentence frames**, pronoun and "the former / the latter" resolution, 9 question formats, narratives with distractor sentences, possession/transfer chains, comparatives | Phase 2, Stage 2B (~0.9 passes) |
56
+ | v3 | — | ~0.3B | *Coming:* v2 plus new sentence structures (reversed questions, passive voice, nested clauses, negation, comparatives, temporal order, part–whole, cause–effect), with some structures held out entirely | Phase 2.5a |
57
+
58
+ \* Tokens counted with the model's tokenizer (SmolLM2 BPE + 12 special tokens). Each row is one document. The generators wrote only unique documents (v1: 2.09M of 4M generated; v2: 3.64M of 5M).
59
+
60
+ **Samples.** From v1:
61
+ > Samir comforted Leo. People who saw it agreed on the reason: Leo was grieving. Nobody thought Samir was grieving; if anything, Samir was patient.
62
+
63
+ From v2:
64
+ > Dov had a notebook. Dov sold it to Odile. Then Odile lent it to Naledi. Now the notebook is with Naledi.
65
+
66
+ > The bowling ball was much heavier, so the bowling ball was harder to carry than the tennis ball. It was Tariq who was confused, which explains why Tariq asked for help from Isaac. Who was confused, Isaac or Tariq? Tariq.
67
+
68
+ ## What happened when we trained on it (honest results)
69
+
70
+ - **v1 was memorized as a template.** Its validation loss fell to ~0.59 within ~500 steps, the model started copying v1 phrases into unrelated generations, and the binding probe didn't move. When v1 was switched off at step 19,000, its validation loss jumped from 0.59 to 1.67, a clear sign of template memorization. **Lesson: one frame is too narrow, however many entities you fill it with.**
71
+ - **v2 transferred to new words and names, but not to new structures.** A held-out probe (v4), built from 4 frames, every 5th entity pair and every 6th name that v2 never contains, rose from **17 → 82 / 112** during the Phase 2 anneal (77 at the final checkpoint; chance ≈ 28). A separate probe built from *different sentence structures* (v3) stayed flat at **4 → 6 / 70**. That gap is what v3 targets.
72
+
73
+ ## Held-out design (no leakage into the probes)
74
+
75
+ - v1 and v2 exclude every frame, entity pair and name used in the evaluation probes. The probe files are listed in each generator's `--probe_files`.
76
+ - v2 additionally holds out 4 frames ("given that", "the trouble was that", "Anyone could tell that", "owing to the fact that"), every 5th entity pair and every 6th name. Those form probe v4. The generator asserts that no held-out frame appears in training text.
77
+
78
+ ## Files
79
+
80
+ | Path | Contents |
81
+ |---|---|
82
+ | `v1/*.parquet`, `v2/*.parquet` | `text` (one document), `version` |
83
+ | `scripts/gen_contrastive.py` | v1 generator |
84
+ | `scripts/gen_contrastive_v2.py` | v2 generator (frames, held-out split, probe v4 builder) |
85
+
86
+ The generators run on CPU in minutes. Use them to regenerate, extend or change the mix.
87
+
88
+ ## Limitations
89
+
90
+ - **Template-generated:** sentence variety is limited to the frames in the generators. That's the exact limitation the results above show.
91
+ - **Names** come from a fixed multicultural list, and attributes from fixed families (emotions, abilities, social roles, sizes, possessions…).
92
+ - **English only.**
93
+
94
+ ## License
95
+
96
+ Apache-2.0. All text is generated by our scripts; no third-party text is included.
97
+
98
+ ## Disclaimer
99
+
100
+ For learning and research purposes only. Provided "AS IS" without warranty, consistent with the Apache License 2.0. AIEDX Private Limited bears no responsibility or liability for any use of this dataset or for any output produced by models trained on it.
scripts/gen_contrastive.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate a synthetic contrastive entity-attribute binding corpus for Phase 2.
2
+
3
+ Why: the 100-case binding probe (benchmark/data/probefinding-winograndestyle/)
4
+ found a flat zero on comparative, emotional and possession/obligation
5
+ attribution, and greedy generation confirmed it ("The marathon took longer
6
+ than the sprint because the sprint was... longer than the marathon"). Passive
7
+ web prose rarely puts BOTH directions of a minimal pair next to each other,
8
+ so next-token prediction never gets pressure to flip the attribute when the
9
+ named entity flips. This corpus does exactly that, densely.
10
+
11
+ Each document states the same situation with the attribute bound to each
12
+ entity, in varied surface forms (paired statements, Q&A, explicit negation,
13
+ short narrative), across five relation families. Entity pairs used by the
14
+ probe set are excluded so the probe remains a held-out measurement.
15
+
16
+ Output: flat uint16 shards (EOT-separated documents), same format as
17
+ src/data/prepare.py, consumed as a `flat` pool by MultiPoolTokenDataset.
18
+
19
+ Usage:
20
+ python scripts/gen_contrastive.py --out_dir /path/phase2/contrastive \
21
+ --n_docs 1500000 --tokenizer_path bubblspace-tokenizer
22
+ """
23
+
24
+ import argparse
25
+ import json
26
+ import random
27
+ from pathlib import Path
28
+
29
+ import numpy as np
30
+ from transformers import AutoTokenizer
31
+
32
+ NAMES = (
33
+ "Aarav Abigail Adaeze Aiko Alejandro Amara Amir Ana Anders Anika Arjun Astrid Ayesha Bao Beatriz "
34
+ "Bilal Camila Carlos Chen Chloe Dante Darius Deepa Diego Dmitri Elena Elif Emeka Emma Esther Fatima "
35
+ "Felix Freya Gabriel Grace Hana Hassan Helena Hiro Ibrahim Ines Isaac Ivan Jamal Jana Javier Jin Joao "
36
+ "Jonas Kai Kamala Karim Kavya Keiko Kenji Kofi Lars Layla Leila Leo Lin Lucia Luis Maya Mehmet Mei "
37
+ "Mira Mohammed Nadia Naledi Nikhil Nina Noor Olu Omar Oscar Pablo Paula Pedro Priya Rafael Ravi Rhea "
38
+ "Rosa Rohan Ruth Sakura Samir Sana Santiago Sara Selin Sergio Shreya Simone Sofia Soren Sunil Tariq "
39
+ "Tess Thabo Tomas Uma Valentina Vikram Wanjiru Wei Xavier Yara Yusuf Zainab Zara Zoe"
40
+ ).split()
41
+
42
+ # ---------------------------------------------------------------- comparative
43
+ # (dimension, [ (more_entity, less_entity), ... ], outcome phrases, more_attr, less_attr)
44
+ COMPARATIVE = [
45
+ ("duration", [("lecture", "coffee break"), ("flight to Sydney", "bus ride across town"), ("winter", "lunch hour"),
46
+ ("movie trilogy", "short film"), ("road trip", "walk to the corner shop"), ("semester", "weekend workshop"),
47
+ ("century", "decade"), ("opera", "pop song"), ("night shift", "quick errand"), ("hike up the mountain", "stroll in the park")],
48
+ ["took longer than the {b}", "lasted longer than the {b}", "used up more of the day than the {b}"],
49
+ ["much longer", "long and drawn out", "far more time-consuming"], ["short", "over quickly", "brief"]),
50
+ ("size", [("whale", "minnow"), ("stadium", "garden shed"), ("oak tree", "seedling"), ("truck", "bicycle"),
51
+ ("mansion", "cottage"), ("continent", "island"), ("watermelon", "grape"), ("airliner", "kite"),
52
+ ("cathedral", "chapel"), ("lake", "puddle")],
53
+ ["took up more space than the {b}", "needed more room than the {b}", "was harder to move than the {b}"],
54
+ ["enormous", "much bigger", "huge"], ["tiny", "much smaller", "small"]),
55
+ ("weight", [("anvil", "feather"), ("piano", "violin"), ("bag of cement", "bag of crisps"), ("bowling ball", "tennis ball"),
56
+ ("motorbike", "skateboard"), ("brick", "sponge"), ("suit of armour", "silk scarf"), ("iron gate", "paper screen")],
57
+ ["was harder to carry than the {b}", "weighed more than the {b}", "bent the shelf more than the {b}"],
58
+ ["very heavy", "much heavier", "dense and heavy"], ["light", "much lighter", "almost weightless"]),
59
+ ("speed", [("cheetah", "tortoise"), ("jet", "hot-air balloon"), ("racing bike", "tricycle"), ("bullet train", "steam engine"),
60
+ ("speedboat", "rowing boat"), ("falcon", "pigeon"), ("motorway", "dirt track"), ("fibre connection", "dial-up modem")],
61
+ ["got there before the {b}", "finished sooner than the {b}", "covered the distance faster than the {b}"],
62
+ ["much faster", "very quick", "built for speed"], ["slow", "much slower", "sluggish"]),
63
+ ("price", [("yacht", "canoe"), ("gold watch", "plastic watch"), ("first-class ticket", "economy ticket"), ("sports stadium", "community hall"),
64
+ ("designer coat", "thrift-store jacket"), ("penthouse", "studio flat"), ("truffle", "potato"), ("original manuscript", "photocopy")],
65
+ ["cost more than the {b}", "sold for a higher price than the {b}", "was harder to afford than the {b}"],
66
+ ["expensive", "far more valuable", "rare and costly"], ["cheap", "inexpensive", "common and cheap"]),
67
+ ("height", [("skyscraper", "bungalow"), ("giraffe", "dachshund"), ("redwood", "shrub"), ("lighthouse", "lamppost"),
68
+ ("mountain", "hill"), ("radio mast", "fence post"), ("basketball player", "toddler"), ("tower crane", "stepladder")],
69
+ ["could be seen from further away than the {b}", "cast a longer shadow than the {b}", "reached higher than the {b}"],
70
+ ["very tall", "much taller", "towering"], ["short", "much shorter", "low"]),
71
+ ("temperature", [("oven", "fridge"), ("desert", "glacier"), ("kettle", "ice tray"), ("summer afternoon", "winter night"),
72
+ ("forge", "cellar"), ("sauna", "swimming pool"), ("engine block", "window pane")],
73
+ ["felt hotter to the touch than the {b}", "melted the butter faster than the {b}", "made people sweat more than the {b}"],
74
+ ["very hot", "much warmer", "scorching"], ["cold", "much cooler", "freezing"]),
75
+ ]
76
+
77
+ # ---------------------------------------------------------------- physical fit
78
+ FIT = [ # (object, container, verb phrase, container_attr, object_attr)
79
+ ("sofa", "lift", "would not fit in the", "too small", "too big"),
80
+ ("grand piano", "hallway", "would not go down the", "too narrow", "too wide"),
81
+ ("bookcase", "car boot", "would not fit in the", "too small", "too large"),
82
+ ("ladder", "shed", "would not stand upright in the", "too low", "too tall"),
83
+ ("boat", "tunnel under the canal", "could not pass through the", "too low", "too tall"),
84
+ ("fridge freezer", "back door", "would not go through the", "too narrow", "too wide"),
85
+ ("double bed", "spare room", "would not fit in the", "too small", "too big"),
86
+ ("lorry", "village lane", "could not drive down the", "too narrow", "too wide"),
87
+ ("christmas tree", "living room", "would not stand up in the", "too low", "too tall"),
88
+ ("cello case", "taxi", "would not fit in the", "too small", "too bulky"),
89
+ ("motor home", "car park", "could not enter the", "too low", "too high"),
90
+ ("rug", "box", "would not fit in the", "too small", "too long"),
91
+ ("dining table", "doorframe", "would not go through the", "too narrow", "too wide"),
92
+ ("surfboard", "elevator", "would not fit in the", "too short", "too long"),
93
+ ]
94
+
95
+ # ---------------------------------------------------------------- person-pair relations
96
+ # (verb phrase, reasons_for_object_person, reasons_for_subject_person)
97
+ EMOTIONAL = [
98
+ ("comforted", ["heartbroken", "grieving", "frightened", "lonely"], ["kind", "caring", "gentle", "patient"]),
99
+ ("thanked", ["helpful", "generous", "supportive", "thoughtful"], ["grateful", "polite", "appreciative", "relieved"]),
100
+ ("apologized to", ["hurt", "upset", "offended", "disappointed"], ["sorry", "ashamed", "remorseful", "guilty"]),
101
+ ("forgave", ["truly sorry", "remorseful", "apologetic", "honest about it"], ["forgiving", "big-hearted", "easygoing", "generous"]),
102
+ ("congratulated", ["successful", "victorious", "promoted", "the winner"], ["proud", "happy for them", "sporting", "warm"]),
103
+ ("reassured", ["anxious", "nervous", "worried", "scared"], ["calm", "confident", "experienced", "steady"]),
104
+ ("scolded", ["careless", "late again", "rude", "reckless"], ["strict", "angry", "frustrated", "impatient"]),
105
+ ("avoided", ["rude", "unpleasant", "dishonest", "boastful"], ["shy", "uncomfortable", "busy", "wary"]),
106
+ ]
107
+ POSSESSION = [
108
+ ("lent money to", ["short of cash", "broke", "behind on rent", "struggling"], ["wealthy", "generous", "well off", "trusting"]),
109
+ ("returned the book to", ["the owner", "asking for it back", "about to move away", "the one who had lent it"], ["finished with it", "honest", "done reading", "careful with borrowed things"]),
110
+ ("paid", ["owed the money", "the one who did the work", "waiting for payment", "the seller"], ["in debt", "the buyer", "honest", "keen to settle up"]),
111
+ ("asked for help from", ["an expert", "strong", "experienced", "good with tools"], ["stuck", "overwhelmed", "new to the job", "confused"]),
112
+ ("gave a gift to", ["celebrating a birthday", "leaving the company", "a close friend", "recovering from illness"], ["thoughtful", "generous", "fond of them", "grateful"]),
113
+ ("borrowed a ladder from", ["the owner of a ladder", "a helpful neighbour", "a builder", "prepared for jobs like this"], ["fixing the roof", "without a ladder", "in the middle of repairs", "short of tools"]),
114
+ ]
115
+ ABILITY = [
116
+ ("beat", ["out of practice", "inexperienced", "tired", "overconfident"], ["well trained", "more skilled", "experienced", "better prepared"]),
117
+ ("taught", ["a beginner", "eager to learn", "new to the subject", "struggling with it"], ["an expert", "experienced", "patient", "qualified"]),
118
+ ("outran", ["slower", "out of shape", "injured", "carrying a heavy bag"], ["faster", "fitter", "a trained sprinter", "well rested"]),
119
+ ("hired", ["highly qualified", "talented", "experienced", "reliable"], ["short-staffed", "expanding", "growing quickly", "in need of help"]),
120
+ ("corrected", ["mistaken", "wrong", "confused", "careless with the figures"], ["an expert", "careful", "certain", "well informed"]),
121
+ ]
122
+
123
+
124
+ def comparative_doc(rng):
125
+ dim, pairs, outcomes, more_attrs, less_attrs = rng.choice(COMPARATIVE)
126
+ a, b = rng.choice(pairs)
127
+ outcome = rng.choice(outcomes).format(b=b)
128
+ more, less = rng.choice(more_attrs), rng.choice(less_attrs)
129
+ head = f"The {a} {outcome}"
130
+ s_a = f"{head} because the {a} was {more}."
131
+ s_b = f"{head} because the {b} was {less}."
132
+ return _style(rng, head, a, b, more, less, s_a, s_b)
133
+
134
+
135
+ def fit_doc(rng):
136
+ obj, cont, vp, cont_attr, obj_attr = rng.choice(FIT)
137
+ head = f"The {obj} {vp} {cont}"
138
+ s_c = f"{head} because the {cont} was {cont_attr}."
139
+ s_o = f"{head} because the {obj} was {obj_attr}."
140
+ return _style(rng, head, cont, obj, cont_attr, obj_attr, s_c, s_o)
141
+
142
+
143
+ def person_doc(rng, frames):
144
+ verb, obj_reasons, subj_reasons = rng.choice(frames)
145
+ x, y = rng.sample(NAMES, 2)
146
+ ro, rs = rng.choice(obj_reasons), rng.choice(subj_reasons)
147
+ head = f"{x} {verb} {y}"
148
+ s_obj = f"{head} because {y} was {ro}."
149
+ s_subj = f"{head} because {x} was {rs}."
150
+ return _style(rng, head, y, x, ro, rs, s_obj, s_subj, people=True)
151
+
152
+
153
+ def _style(rng, head, e1, e2, attr1, attr2, s1, s2, people=False):
154
+ """e1 carries attr1 (sentence s1), e2 carries attr2 (sentence s2)."""
155
+ the1 = e1 if people else f"the {e1}"
156
+ the2 = e2 if people else f"the {e2}"
157
+ style = rng.randrange(6)
158
+ if style == 0: # paired statements, random order
159
+ return " ".join(rng.sample([s1, s2], 2))
160
+ if style == 1: # explicit contrast
161
+ return f"{s1} Put the other way around: {s2}"
162
+ if style == 2: # Q&A
163
+ return (f"Question: {head}. Which one was {attr1}? Answer: {the1.capitalize() if not people else the1}. "
164
+ f"Which one was {attr2}? Answer: {the2.capitalize() if not people else the2}.")
165
+ if style == 3: # negation
166
+ return (f"{head}, and it was not because {the2} was {attr1}. "
167
+ f"{the1[0].upper() + the1[1:]} was {attr1}, while {the2} was {attr2}.")
168
+ if style == 4: # single direction only (keeps the corpus from being trivially paired)
169
+ return rng.choice([s1, s2])
170
+ # style 5: short narrative
171
+ return (f"{head}. People who saw it agreed on the reason: {the1} was {attr1}. "
172
+ f"Nobody thought {the2} was {attr1}; if anything, {the2} was {attr2}.")
173
+
174
+
175
+ def load_probe_contexts(probe_files):
176
+ ctxs = []
177
+ for pf in probe_files:
178
+ data = json.loads(Path(pf).read_text())
179
+ for c in data["cases"]:
180
+ ctxs.append((c["ctxA"] + " " + c["ctxB"]).lower())
181
+ return ctxs
182
+
183
+
184
+ def main():
185
+ ap = argparse.ArgumentParser()
186
+ ap.add_argument("--out_dir", required=True)
187
+ ap.add_argument("--n_docs", type=int, default=1_500_000)
188
+ ap.add_argument("--tokenizer_path", default="bubblspace-tokenizer")
189
+ ap.add_argument("--shard_tokens", type=int, default=100_000_000)
190
+ ap.add_argument("--seed", type=int, default=1234)
191
+ ap.add_argument("--probe_files", nargs="*", default=[])
192
+ args = ap.parse_args()
193
+
194
+ # contamination guard, so the probe stays a held-out measurement:
195
+ # (1) no generator entity PAIR may co-occur in any probe sentence;
196
+ # (2) no person name used in the probe may appear in generated docs.
197
+ probe_ctxs = load_probe_contexts(args.probe_files)
198
+ gen_pairs = [(a, b) for _, ps, *_ in COMPARATIVE for a, b in ps] + [(o, c) for o, c, *_ in FIT]
199
+ overlap = [(a, b) for a, b in gen_pairs if any(f" {a.lower()} " in f" {c} " and f" {b.lower()} " in f" {c} " for c in probe_ctxs)]
200
+ assert not overlap, f"generator entity pairs co-occur in probe cases: {overlap}"
201
+ probe_text = " ".join(probe_ctxs)
202
+ dropped = [n for n in NAMES if f" {n.lower()} " in f" {probe_text} "]
203
+ NAMES[:] = [n for n in NAMES if n not in dropped]
204
+ print(f"[guard] dropped probe names from generator: {dropped}; {len(NAMES)} names remain")
205
+
206
+ rng = random.Random(args.seed)
207
+ tok = AutoTokenizer.from_pretrained(args.tokenizer_path)
208
+ eot = tok.eos_token_id
209
+ out = Path(args.out_dir)
210
+ out.mkdir(parents=True, exist_ok=True)
211
+
212
+ makers = [
213
+ (0.30, comparative_doc),
214
+ (0.15, fit_doc),
215
+ (0.20, lambda r: person_doc(r, EMOTIONAL)),
216
+ (0.20, lambda r: person_doc(r, POSSESSION)),
217
+ (0.15, lambda r: person_doc(r, ABILITY)),
218
+ ]
219
+ weights = [w for w, _ in makers]
220
+
221
+ buf = np.empty(args.shard_tokens, dtype=np.uint16)
222
+ pos, shard, total, unique = 0, 0, 0, set()
223
+ batch = []
224
+
225
+ def flush_batch():
226
+ nonlocal pos, shard, total
227
+ for ids in tok(batch, add_special_tokens=False)["input_ids"]:
228
+ ids = ids + [eot]
229
+ if pos + len(ids) > args.shard_tokens:
230
+ buf[:pos].tofile(out / f"shard_{shard:05d}.bin"); shard += 1; pos = 0
231
+ buf[pos : pos + len(ids)] = ids
232
+ pos += len(ids)
233
+ total += len(ids)
234
+ batch.clear()
235
+
236
+ # n_docs = generation ATTEMPTS; only unique documents are written, so
237
+ # small template families (e.g. physical fit) cannot dominate by sheer
238
+ # duplication. Repetition is controlled later by the pool's sampling weight.
239
+ for i in range(args.n_docs):
240
+ doc = rng.choices(makers, weights=weights)[0][1](rng)
241
+ if doc in unique:
242
+ continue
243
+ unique.add(doc)
244
+ batch.append(doc)
245
+ if len(batch) >= 10_000:
246
+ flush_batch()
247
+ if batch:
248
+ flush_batch()
249
+ if pos:
250
+ buf[:pos].tofile(out / f"shard_{shard:05d}.bin"); shard += 1
251
+
252
+ meta = {
253
+ "dataset": "synthetic_contrastive_binding",
254
+ "tokenizer_path": args.tokenizer_path,
255
+ "total_tokens": total,
256
+ "n_docs": args.n_docs,
257
+ "unique_docs": len(unique),
258
+ "n_shards": shard,
259
+ "dtype": "uint16",
260
+ "eot_token": eot,
261
+ "real_vocab_size": len(tok),
262
+ "is_code": False,
263
+ "fim_rate": 0.0,
264
+ "probe_exclusion_files": args.probe_files,
265
+ }
266
+ (out / "meta.json").write_text(json.dumps(meta, indent=2))
267
+ print(json.dumps(meta, indent=2))
268
+
269
+
270
+ if __name__ == "__main__":
271
+ main()
scripts/gen_contrastive_v2.py ADDED
@@ -0,0 +1,493 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Contrastive entity-attribute binding corpus, v2 (for the Phase 2 anneal).
2
+
3
+ Why v2: the v1 corpus (scripts/gen_contrastive.py) expresses every fact with
4
+ one frame ("{event} because {entity} was {attr}") inside 6 fixed wrappers, two
5
+ of them with fixed phrases ("Put the other way around:", "People who saw it
6
+ agreed"). Its validation loss flattened at ~0.59 by Phase 2 step ~500 and the
7
+ model began reproducing those phrases in free generation, while probe v3
8
+ (different sentence structures) did not move. The model learned the template,
9
+ not the binding.
10
+
11
+ v2 keeps the target (the attribute must follow the right entity) and removes
12
+ the template:
13
+ * 15 training sentence frames for "event + reason" (fronted, consequence,
14
+ cleft, semicolon, ...), no single wrapper phrase.
15
+ * Pronoun and former/latter frames with explicit resolution (Winograd-style
16
+ reference, which v1 never trained).
17
+ * Document shapes: single statement, both directions with varied
18
+ connectives, corrections, varied Q&A/dialogue formats, narrative embedding
19
+ with distractor sentences, two situations per document, and multi-step
20
+ possession tracking.
21
+ * Larger inventories (more dimensions, objects, relations).
22
+ * Held out for evaluation (never in training): 4 sentence frames, ~20% of
23
+ entity pairs per family, ~1/6 of names. --probe_out writes a probe (v4)
24
+ built only from held-out frames + entities, in the probe_entity_binding.py
25
+ format, to measure template-free transfer.
26
+
27
+ Contamination guards (asserted): no generator entity pair co-occurs in a
28
+ probe v2/v3 context; probe names are removed; no probe v3 frame phrase and no
29
+ held-out frame phrase appears in any training document.
30
+
31
+ Usage:
32
+ python scripts/gen_contrastive_v2.py --out_dir /path/phase2/contrastive_v2 \
33
+ --n_docs 2000000 --probe_files <v2.json> <v3.json> --probe_out probe_v4.json
34
+ """
35
+
36
+ import argparse
37
+ import json
38
+ import random
39
+ from dataclasses import dataclass
40
+ from pathlib import Path
41
+
42
+ import numpy as np
43
+
44
+ NAMES = (
45
+ "Aarav Abigail Adaeze Aiko Alejandro Amara Amir Ana Anders Anika Arjun Astrid Ayesha Bao Beatriz "
46
+ "Bilal Camila Chen Chloe Dante Darius Deepa Diego Dmitri Elena Elif Emeka Esther Fatima "
47
+ "Felix Freya Gabriel Hana Hassan Helena Hiro Ibrahim Ines Isaac Ivan Jamal Jana Javier Jin Joao "
48
+ "Jonas Kai Kamala Karim Kavya Keiko Kenji Kofi Lars Layla Leila Leo Lin Lucia Luis Maya Mehmet Mei "
49
+ "Mira Mohammed Nadia Naledi Nikhil Nina Noor Olu Omar Oscar Pablo Paula Pedro Rafael Ravi Rhea "
50
+ "Rosa Rohan Ruth Sakura Samir Sana Santiago Sara Selin Sergio Shreya Simone Sofia Soren Sunil Tariq "
51
+ "Tess Thabo Tomas Uma Valentina Vikram Wanjiru Xavier Yara Yusuf Zainab Zara Zoe Ada Bruno Cyrus "
52
+ "Dalia Ezra Farah Gideon Hugo Ilse Jude Kiran Lena Marco Nils Odile Pia Quinn Reza Saskia Teo "
53
+ "Ulla Vera Wren Yosef Zeno Anouk Basil Clio Dov Emil Fern Gus Hedda Ike Juno Kasimir Lotte"
54
+ ).split()
55
+
56
+ # comparative: (dimension, pairs (more, less), event templates with {a} {b}, more attrs, less attrs)
57
+ COMPARATIVE = [
58
+ ("duration", [("lecture", "coffee break"), ("flight to Sydney", "bus ride across town"), ("winter", "lunch hour"),
59
+ ("movie trilogy", "short film"), ("road trip", "walk to the corner shop"), ("semester", "weekend workshop"),
60
+ ("century", "decade"), ("opera", "pop song"), ("night shift", "quick errand"), ("hike up the mountain", "stroll in the park"),
61
+ ("board meeting", "phone call"), ("ocean voyage", "ferry crossing"), ("chess tournament", "card trick"), ("novel", "postcard")],
62
+ ["The {a} took longer than the {b}", "The {a} lasted longer than the {b}", "The {a} used up more of the day than the {b}",
63
+ "People spent more time on the {a} than on the {b}"],
64
+ ["much longer", "long and drawn out", "far more time-consuming", "very lengthy"], ["short", "over quickly", "brief", "quick"]),
65
+ ("size", [("whale", "minnow"), ("stadium", "garden shed"), ("oak tree", "seedling"), ("truck", "bicycle"),
66
+ ("mansion", "cottage"), ("continent", "island"), ("watermelon", "grape"), ("airliner", "kite"),
67
+ ("cathedral", "chapel"), ("lake", "puddle"), ("warehouse", "kiosk"), ("elephant", "mouse"), ("galleon", "dinghy")],
68
+ ["The {a} took up more space than the {b}", "The {a} needed more room than the {b}", "The {a} was harder to move than the {b}",
69
+ "Fitting the {a} in the photo was harder than fitting the {b}"],
70
+ ["enormous", "much bigger", "huge", "massive"], ["tiny", "much smaller", "small", "compact"]),
71
+ ("weight", [("anvil", "feather"), ("piano", "violin"), ("bag of cement", "bag of crisps"), ("bowling ball", "tennis ball"),
72
+ ("motorbike", "skateboard"), ("brick", "sponge"), ("suit of armour", "silk scarf"), ("iron gate", "paper screen"),
73
+ ("marble statue", "cardboard cutout"), ("crate of books", "box of tissues")],
74
+ ["The {a} was harder to carry than the {b}", "The {a} weighed more than the {b}", "The {a} bent the shelf more than the {b}",
75
+ "Lifting the {a} took more effort than lifting the {b}"],
76
+ ["very heavy", "much heavier", "dense and heavy", "a real burden"], ["light", "much lighter", "almost weightless", "easy to lift"]),
77
+ ("speed", [("cheetah", "tortoise"), ("jet", "hot-air balloon"), ("racing bike", "tricycle"), ("bullet train", "steam engine"),
78
+ ("speedboat", "rowing boat"), ("falcon", "pigeon"), ("motorway", "dirt track"), ("fibre connection", "dial-up modem"),
79
+ ("express courier", "surface mail"), ("hare", "snail")],
80
+ ["The {a} got there before the {b}", "The {a} finished sooner than the {b}", "The {a} covered the distance faster than the {b}",
81
+ "The {b} arrived long after the {a}"],
82
+ ["much faster", "very quick", "built for speed", "rapid"], ["slow", "much slower", "sluggish", "unhurried"]),
83
+ ("price", [("yacht", "canoe"), ("gold watch", "plastic watch"), ("first-class ticket", "economy ticket"), ("sports stadium", "community hall"),
84
+ ("designer coat", "thrift-store jacket"), ("penthouse", "studio flat"), ("truffle", "potato"), ("original manuscript", "photocopy"),
85
+ ("diamond ring", "paper clip"), ("sports car", "scooter")],
86
+ ["The {a} cost more than the {b}", "The {a} sold for a higher price than the {b}", "The {a} was harder to afford than the {b}",
87
+ "Buyers saved for months for the {a} but not for the {b}"],
88
+ ["expensive", "far more valuable", "rare and costly", "pricey"], ["cheap", "inexpensive", "common and cheap", "affordable"]),
89
+ ("height", [("skyscraper", "bungalow"), ("giraffe", "dachshund"), ("redwood", "shrub"), ("lighthouse", "lamppost"),
90
+ ("mountain", "hill"), ("radio mast", "fence post"), ("basketball player", "toddler"), ("tower crane", "stepladder"),
91
+ ("church spire", "garden wall"), ("palm tree", "fern")],
92
+ ["The {a} could be seen from further away than the {b}", "The {a} cast a longer shadow than the {b}", "The {a} reached higher than the {b}"],
93
+ ["very tall", "much taller", "towering", "lofty"], ["short", "much shorter", "low", "squat"]),
94
+ ("temperature", [("oven", "fridge"), ("desert", "glacier"), ("kettle", "ice tray"), ("summer afternoon", "winter night"),
95
+ ("forge", "cellar"), ("sauna", "swimming pool"), ("engine block", "window pane"), ("radiator", "marble floor")],
96
+ ["The {a} felt hotter to the touch than the {b}", "The {a} melted the butter faster than the {b}", "The {a} made people sweat more than the {b}"],
97
+ ["very hot", "much warmer", "scorching", "baking"], ["cold", "much cooler", "freezing", "chilly"]),
98
+ ("loudness", [("jackhammer", "whisper"), ("drum kit", "flute"), ("thunderclap", "rustling leaf"), ("fire alarm", "ticking clock"),
99
+ ("rock concert", "library"), ("jet engine", "desk fan")],
100
+ ["The {a} drowned out the {b}", "The {a} could be heard further away than the {b}", "The {a} woke the baby but the {b} did not"],
101
+ ["deafening", "very loud", "noisy", "booming"], ["quiet", "faint", "soft", "barely audible"]),
102
+ ("age", [("castle", "car park"), ("fossil", "newspaper"), ("cathedral", "shopping mall"), ("Roman road", "cycle lane"),
103
+ ("manuscript", "text message"), ("pyramid", "petrol station")],
104
+ ["The {a} had seen far more history than the {b}", "The {a} appeared in older records than the {b}", "The {a} predated the {b}"],
105
+ ["ancient", "very old", "centuries old", "much older"], ["new", "recent", "modern", "much newer"]),
106
+ ("brightness", [("searchlight", "candle"), ("noon sun", "crescent moon"), ("stadium floodlight", "night light"), ("flare", "glow-worm")],
107
+ ["The {a} lit up more of the field than the {b}", "The {a} was easier to see from afar than the {b}", "The {a} hurt the eyes more than the {b}"],
108
+ ["dazzling", "very bright", "blinding", "brilliant"], ["dim", "faint", "weak", "soft"]),
109
+ ]
110
+
111
+ # physical fit: (object, container, event verb phrase, container attr, object attr)
112
+ FIT = [
113
+ ("sofa", "lift", "would not fit in the", "too small", "too big"),
114
+ ("grand piano", "hallway", "would not go down the", "too narrow", "too wide"),
115
+ ("bookcase", "car boot", "would not fit in the", "too small", "too large"),
116
+ ("ladder", "shed", "would not stand upright in the", "too low", "too tall"),
117
+ ("barge", "tunnel under the canal", "could not pass through the", "too low", "too tall"),
118
+ ("fridge freezer", "back door", "would not go through the", "too narrow", "too wide"),
119
+ ("double bed", "spare room", "would not fit in the", "too small", "too big"),
120
+ ("lorry", "village lane", "could not drive down the", "too narrow", "too wide"),
121
+ ("Christmas tree", "living room", "would not stand up in the", "too low", "too tall"),
122
+ ("cello case", "taxi", "would not fit in the", "too small", "too bulky"),
123
+ ("motor home", "multi-storey car park", "could not enter the", "too low", "too high"),
124
+ ("rug", "box", "would not fit in the", "too small", "too long"),
125
+ ("dining table", "doorframe", "would not go through the", "too narrow", "too wide"),
126
+ ("surfboard", "lift", "would not fit in the", "too short", "too long"),
127
+ ("canoe", "garage", "would not fit in the", "too short", "too long"),
128
+ ("giraffe", "horse trailer", "would not fit in the", "too low", "too tall"),
129
+ ("aquarium", "alcove", "would not fit in the", "too narrow", "too wide"),
130
+ ("wardrobe", "stairwell", "could not be carried up the", "too narrow", "too bulky"),
131
+ ("trampoline", "back garden", "would not fit in the", "too small", "too big"),
132
+ ("harp", "hatchback", "would not fit in the", "too small", "too tall"),
133
+ ]
134
+
135
+ # person pairs: (verb, reasons for the OBJECT person, reasons for the SUBJECT person)
136
+ EMOTIONAL = [
137
+ ("comforted", ["heartbroken", "grieving", "frightened", "lonely"], ["kind", "caring", "gentle", "patient"]),
138
+ ("thanked", ["helpful", "generous", "supportive", "thoughtful"], ["grateful", "polite", "appreciative", "relieved"]),
139
+ ("apologized to", ["hurt", "upset", "offended", "disappointed"], ["sorry", "ashamed", "remorseful", "guilty"]),
140
+ ("forgave", ["truly sorry", "remorseful", "apologetic", "honest about it"], ["forgiving", "big-hearted", "easygoing", "generous"]),
141
+ ("congratulated", ["successful", "victorious", "promoted", "the winner"], ["proud", "happy for them", "sporting", "warm"]),
142
+ ("reassured", ["anxious", "nervous", "worried", "scared"], ["calm", "confident", "experienced", "steady"]),
143
+ ("scolded", ["careless", "late again", "rude", "reckless"], ["strict", "angry", "frustrated", "impatient"]),
144
+ ("avoided", ["rude", "unpleasant", "dishonest", "boastful"], ["shy", "uncomfortable", "busy", "wary"]),
145
+ ("cheered up", ["gloomy", "downcast", "miserable", "feeling low"], ["cheerful", "funny", "upbeat", "good-humoured"]),
146
+ ("envied", ["admired by everyone", "very successful", "lucky", "popular"], ["insecure", "jealous", "unhappy with their own life", "resentful"]),
147
+ ]
148
+ POSSESSION = [
149
+ ("lent money to", ["short of cash", "broke", "behind on rent", "struggling"], ["wealthy", "generous", "well off", "trusting"]),
150
+ ("returned the book to", ["the owner", "asking for it back", "about to move away", "the one who had lent it"], ["finished with it", "honest", "done reading", "careful with borrowed things"]),
151
+ ("paid", ["owed the money", "the one who did the work", "waiting for payment", "the seller"], ["in debt", "the buyer", "honest", "keen to settle up"]),
152
+ ("asked for help from", ["an expert", "strong", "experienced", "good with tools"], ["stuck", "overwhelmed", "new to the job", "confused"]),
153
+ ("gave a gift to", ["celebrating a birthday", "leaving the company", "a close friend", "recovering from illness"], ["thoughtful", "generous", "fond of them", "grateful"]),
154
+ ("borrowed a ladder from", ["the owner of a ladder", "a helpful neighbour", "a builder", "prepared for jobs like this"], ["fixing the roof", "without a ladder", "in the middle of repairs", "short of tools"]),
155
+ ("sold a bicycle to", ["looking for a cheap ride", "a keen cyclist", "in need of transport", "the buyer"], ["moving abroad", "short of space", "the seller", "upgrading to a car"]),
156
+ ("rented a room to", ["a student", "new in town", "looking for a place to stay", "the tenant"], ["the landlord", "the owner of a big house", "living alone", "glad of the income"]),
157
+ ]
158
+ ABILITY = [
159
+ ("beat", ["out of practice", "inexperienced", "tired", "overconfident"], ["well trained", "more skilled", "experienced", "better prepared"]),
160
+ ("taught", ["a beginner", "eager to learn", "new to the subject", "struggling with it"], ["an expert", "experienced", "patient", "qualified"]),
161
+ ("outran", ["slower", "out of shape", "injured", "carrying a heavy bag"], ["faster", "fitter", "a trained sprinter", "well rested"]),
162
+ ("hired", ["highly qualified", "talented", "experienced", "reliable"], ["short-staffed", "expanding", "growing quickly", "in need of help"]),
163
+ ("corrected", ["mistaken", "wrong", "confused", "careless with the figures"], ["an expert", "careful", "certain", "well informed"]),
164
+ ("rescued", ["stranded", "in danger", "trapped", "lost"], ["brave", "a trained lifeguard", "strong", "quick-thinking"]),
165
+ ("tutored", ["behind in maths", "struggling at school", "preparing for an exam", "a slow reader"], ["a gifted student", "a former teacher", "patient", "top of the class"]),
166
+ ]
167
+ ITEMS = ["umbrella", "camera", "notebook", "guitar", "torch", "map", "key", "scarf", "telescope", "kettle", "hammer", "chessboard"]
168
+
169
+ # sentence frames (training). Each: f(event, event_lc, E, A, people) -> sentence
170
+ def _cap(s):
171
+ return s[0].upper() + s[1:]
172
+
173
+ TRAIN_FRAMES = [
174
+ lambda ev, lc, E, A, p: f"{ev} because {E} was {A}.",
175
+ lambda ev, lc, E, A, p: f"{ev}, since {E} was {A}.",
176
+ lambda ev, lc, E, A, p: f"{ev} as {E} was {A}.",
177
+ lambda ev, lc, E, A, p: f"Because {E} was {A}, {lc}.",
178
+ lambda ev, lc, E, A, p: f"Since {E} was {A}, {lc}.",
179
+ lambda ev, lc, E, A, p: f"{_cap(E)} was {A}, so {lc}.",
180
+ lambda ev, lc, E, A, p: f"{_cap(E)} was {A}, and that is why {lc}.",
181
+ lambda ev, lc, E, A, p: f"{ev}. The reason: {E} was {A}.",
182
+ lambda ev, lc, E, A, p: f"{ev}; {E} was {A}.",
183
+ lambda ev, lc, E, A, p: f"{ev}, simply because {E} was {A}.",
184
+ lambda ev, lc, E, A, p: f"{ev}, which happened because {E} was {A}.",
185
+ lambda ev, lc, E, A, p: f"{ev}. Why? {_cap(E)} was {A}.",
186
+ lambda ev, lc, E, A, p: f"{ev} for one reason: {E} was {A}.",
187
+ lambda ev, lc, E, A, p: f"{ev}, mainly because {E} was {A}.",
188
+ lambda ev, lc, E, A, p: f"It was {E} {'who' if p else 'that'} was {A}, which explains why {lc}.",
189
+ ]
190
+ # held-out frames: evaluation only (probe v4), never in training. Prefix ends right before the attribute.
191
+ HELDOUT_FRAMES = [
192
+ lambda ev, E: f"{ev}, given that {E} was",
193
+ lambda ev, E: f"{ev}; the trouble was that {E} was",
194
+ lambda ev, E: f"{ev}. Anyone could tell that {E} was",
195
+ lambda ev, E: f"{ev}, owing to the fact that {E} was",
196
+ ]
197
+ BANNED_IN_TRAIN = ["given that", "the trouble was", "anyone could tell", "owing to", # held-out frames
198
+ "the one that was", "the person who was", "of the two", "was clearly the", # probe v3 frames
199
+ "put the other way around", "people who saw it agreed"] # v1 fixed phrases
200
+
201
+ BOTH_CONNECTIVES = ["", "Also, ", "And ", "At the same time, ", "Equally, ", "It is also true that ", "Seen from the other side, ",
202
+ "Looking at it the other way, ", "Likewise, ", "On top of that, ", "From the other angle, ", "Add to that: "]
203
+ FILLERS = ["It was a {day} {time}.", "The street outside was quiet.", "Rain had been falling since early morning.", "Nobody was in a hurry that day.",
204
+ "A {thing} lay forgotten on the table.", "Someone had left the radio on.", "The {day} market was busy as usual.",
205
+ "It had been a long week for everyone.", "A dog barked somewhere down the road.", "The {thing} on the shelf had not moved in years.",
206
+ "Later that {time}, everyone went home.", "The news spread quickly.", "Nothing else about the day was unusual."]
207
+ DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
208
+ TIMES = ["morning", "afternoon", "evening"]
209
+ THINGS = ["vase", "newspaper", "teacup", "pencil", "clock", "coat", "basket", "lamp"]
210
+
211
+
212
+ @dataclass
213
+ class Sit:
214
+ event: str # main clause, no final period
215
+ e1: str # entity with a1 (with determiner, or a name)
216
+ e2: str
217
+ a1: str
218
+ a2: str
219
+ people: bool
220
+ first: int # which of (1, 2) is mentioned first in the event
221
+ family: str
222
+
223
+
224
+ def _lc(ev, people):
225
+ return ev if people else ev[0].lower() + ev[1:]
226
+
227
+
228
+ def split_holdout(seq, every=5):
229
+ train = [x for i, x in enumerate(seq) if i % every != every - 1]
230
+ held = [x for i, x in enumerate(seq) if i % every == every - 1]
231
+ return train, held
232
+
233
+
234
+ def make_sit(rng, family, pairs_or_frames, names):
235
+ if family == "comparative":
236
+ dim, pairs, events, mores, lesses = pairs_or_frames
237
+ a, b = rng.choice(pairs)
238
+ ev = rng.choice(events).format(a=a, b=b)
239
+ first = 1 if ev.index(a) < ev.index(b) else 2
240
+ return Sit(ev, f"the {a}", f"the {b}", rng.choice(mores), rng.choice(lesses), False, first, "comparative")
241
+ if family == "fit":
242
+ obj, cont, vp, ca, oa = pairs_or_frames
243
+ return Sit(f"The {obj} {vp} {cont}", f"the {cont}", f"the {obj}", ca, oa, False, 2, "fit")
244
+ verb, obj_r, subj_r = pairs_or_frames
245
+ x, y = rng.sample(names, 2)
246
+ return Sit(f"{x} {verb} {y}", y, x, rng.choice(obj_r), rng.choice(subj_r), True, 2, family)
247
+
248
+
249
+ def statement(rng, s, which):
250
+ E, A = (s.e1, s.a1) if which == 1 else (s.e2, s.a2)
251
+ return rng.choice(TRAIN_FRAMES)(s.event, _lc(s.event, s.people), E, A, s.people)
252
+
253
+
254
+ def pronoun_statement(rng, s, which):
255
+ E, A = (s.e1, s.a1) if which == 1 else (s.e2, s.a2)
256
+ if s.people:
257
+ ref = "the former" if which == s.first else "the latter"
258
+ return f"{s.event} because {ref} was {A}. Here, \"{ref}\" refers to {E}."
259
+ res = rng.choice([f"Here, \"it\" refers to {E}.", f"In that sentence, \"it\" means {E}.", f"(\"It\" is {E}.)"])
260
+ return f"{s.event} because it was {A}. {res}"
261
+
262
+
263
+ def question(rng, s, which):
264
+ E, A = (s.e1, s.a1) if which == 1 else (s.e2, s.a2)
265
+ O = s.e2 if which == 1 else s.e1
266
+ who = "Who" if s.people else "Which"
267
+ x, y = rng.sample([E, O], 2)
268
+ fmt = rng.randrange(9)
269
+ if fmt == 0:
270
+ return f"Q: {who} was {A}? A: {_cap(E)}."
271
+ if fmt == 1:
272
+ return f"\"{who} was {A}?\" someone asked. \"{_cap(E)},\" came the reply."
273
+ if fmt == 2:
274
+ return f"Quiz: {who.lower()} was {A}? Answer: {E}."
275
+ if fmt == 3:
276
+ return f"If you are asked {who.lower()} was {A}, the answer is {E}."
277
+ if fmt == 4:
278
+ return f"{who} was {A}, {x} or {y}? {_cap(E)}."
279
+ if fmt == 5:
280
+ return f"{_cap(x)} or {y}: {who.lower()} was {A}? {_cap(E)}, clearly."
281
+ if fmt == 6:
282
+ return f"Check: {who.lower()} was {A}? {_cap(E)}."
283
+ if fmt == 7:
284
+ return f"So {who.lower()} was {A}? That would be {E}."
285
+ return f"{who} was {A}? {_cap(E)}."
286
+
287
+
288
+ def filler(rng):
289
+ return rng.choice(FILLERS).format(day=rng.choice(DAYS), time=rng.choice(TIMES), thing=rng.choice(THINGS))
290
+
291
+
292
+ def correction(rng, s, which):
293
+ E, A = (s.e1, s.a1) if which == 1 else (s.e2, s.a2)
294
+ O = s.e2 if which == 1 else s.e1
295
+ fmt = rng.randrange(4)
296
+ if fmt == 0:
297
+ return f"{s.event}. It was not that {O} was {A}; {E} was {A}."
298
+ if fmt == 1:
299
+ return f"{s.event}. Was {O} {A}? No. {_cap(E)} was."
300
+ if fmt == 2:
301
+ return f"{s.event}. Some might guess {O} was {A}, but in fact {E} was {A}."
302
+ return f"{s.event}. It was {E}, not {O}, {'who' if s.people else 'that'} was {A}."
303
+
304
+
305
+ def possession_chain(rng, names):
306
+ item = rng.choice(ITEMS)
307
+ people = rng.sample(names, rng.randint(3, 4))
308
+ verbs = ["gave it to", "lent it to", "passed it to", "handed it to", "sold it to"]
309
+ parts = [f"{people[0]} had a {item}."]
310
+ for i in range(1, len(people)):
311
+ parts.append(f"{'Then ' if i > 1 else ''}{people[i - 1]} {rng.choice(verbs)} {people[i]}.")
312
+ end = rng.randrange(3)
313
+ if end == 0:
314
+ parts.append(f"Now the {item} is with {people[-1]}.")
315
+ elif end == 1:
316
+ parts.append(f"Q: Who has the {item} now? A: {people[-1]}. Q: Who had it first? A: {people[0]}.")
317
+ else:
318
+ parts.append(f"So {people[-1]} has the {item}, and {people[0]} no longer does.")
319
+ return " ".join(parts)
320
+
321
+
322
+ def document(rng, fam_pool, names):
323
+ if rng.random() < 0.08:
324
+ return possession_chain(rng, names)
325
+ fam, spec = rng.choice(fam_pool)
326
+ s = make_sit(rng, fam, spec, names)
327
+ w = rng.choice([1, 2])
328
+ shape = rng.randrange(9)
329
+ if shape == 0: # single statement
330
+ return statement(rng, s, w)
331
+ if shape == 1: # both directions, varied connective
332
+ c = rng.choice(BOTH_CONNECTIVES)
333
+ second = statement(rng, s, 3 - w)
334
+ if c and second.split()[0] not in NAMES: # keep names capitalized
335
+ second = second[0].lower() + second[1:]
336
+ return f"{statement(rng, s, w)} {c}{second}"
337
+ if shape == 2: # correction
338
+ return correction(rng, s, w)
339
+ if shape == 3: # statement + question(s)
340
+ out = [statement(rng, s, w), question(rng, s, w)]
341
+ if rng.random() < 0.5:
342
+ out.append(question(rng, s, 3 - w))
343
+ return " ".join(out)
344
+ if shape == 4: # narrative embedding with distractors
345
+ fl = list(dict.fromkeys(filler(rng) for _ in range(3)))
346
+ body = fl[:rng.randint(1, 2)] + [statement(rng, s, w)]
347
+ if rng.random() < 0.5 and len(fl) > 2:
348
+ body.append(fl[2])
349
+ return " ".join(body)
350
+ if shape == 5: # pronoun / former-latter with resolution
351
+ return pronoun_statement(rng, s, w)
352
+ if shape == 6: # two situations, then a question about one
353
+ fam2, spec2 = rng.choice(fam_pool)
354
+ s2 = make_sit(rng, fam2, spec2, names)
355
+ w2 = rng.choice([1, 2])
356
+ target, tw = rng.choice([(s, w), (s2, w2)])
357
+ return f"{statement(rng, s, w)} {statement(rng, s2, w2)} {question(rng, target, tw)}"
358
+ if shape == 7: # both directions, both as questions
359
+ return f"{s.event}. {question(rng, s, 1)} {question(rng, s, 2)}"
360
+ return f"{statement(rng, s, w)} {filler(rng)} {question(rng, s, w)}"
361
+
362
+
363
+ def load_probe_contexts(probe_files):
364
+ ctxs = []
365
+ for pf in probe_files:
366
+ for c in json.loads(Path(pf).read_text())["cases"]:
367
+ ctxs.append((c["ctxA"] + " " + c["ctxB"]).lower())
368
+ return ctxs
369
+
370
+
371
+ def build_probe_v4(rng, held_pool, held_names, n_per_family=24):
372
+ cases = []
373
+ by_fam = {}
374
+ for fam, spec in held_pool:
375
+ by_fam.setdefault(fam, []).append(spec)
376
+ for fam, specs in sorted(by_fam.items()):
377
+ seen = set()
378
+ tries = 0
379
+ while sum(1 for c in cases if c["category"] == fam) < n_per_family and tries < 5000:
380
+ tries += 1
381
+ s = make_sit(rng, fam, rng.choice(specs), held_names)
382
+ frame = rng.choice(HELDOUT_FRAMES)
383
+ ctxA, ctxB = frame(s.event, s.e1), frame(s.event, s.e2)
384
+ if ctxA in seen:
385
+ continue
386
+ seen.add(ctxA)
387
+ cases.append({"name": f"v4-{fam}-{len(cases)}", "category": fam, "ctxA": ctxA, "ctxB": ctxB,
388
+ "c1": f" {s.a1}.", "c2": f" {s.a2}."})
389
+ return cases
390
+
391
+
392
+ def main():
393
+ ap = argparse.ArgumentParser()
394
+ ap.add_argument("--out_dir", required=True)
395
+ ap.add_argument("--n_docs", type=int, default=2_000_000)
396
+ ap.add_argument("--tokenizer_path", default="bubblspace-tokenizer")
397
+ ap.add_argument("--shard_tokens", type=int, default=100_000_000)
398
+ ap.add_argument("--seed", type=int, default=20261122)
399
+ ap.add_argument("--probe_files", nargs="*", default=[])
400
+ ap.add_argument("--probe_out", default=None)
401
+ ap.add_argument("--dry_run", type=int, default=0, help="print N sample docs and exit")
402
+ args = ap.parse_args()
403
+
404
+ # guard 1: probe names never appear in generated docs
405
+ probe_ctxs = load_probe_contexts(args.probe_files)
406
+ probe_text = " " + " ".join(probe_ctxs) + " "
407
+ names = [n for n in NAMES if f" {n.lower()} " not in probe_text and f" {n.lower()}." not in probe_text]
408
+ print(f"[guard] dropped {len(NAMES) - len(names)} probe names; {len(names)} remain")
409
+ train_names, held_names = split_holdout(names, every=6)
410
+
411
+ # hold out ~20% of entity pairs / relation frames per family for probe v4
412
+ train_pool, held_pool = [], []
413
+ for dim, pairs, events, mores, lesses in COMPARATIVE:
414
+ tr, he = split_holdout(pairs)
415
+ train_pool.append(("comparative", (dim, tr, events, mores, lesses)))
416
+ if he:
417
+ held_pool.append(("comparative", (dim, he, events, mores, lesses)))
418
+ tr, he = split_holdout(FIT)
419
+ train_pool += [("fit", f) for f in tr]
420
+ held_pool += [("fit", f) for f in he]
421
+ for fam, frames in (("emotional", EMOTIONAL), ("possession", POSSESSION), ("ability", ABILITY)):
422
+ tr, he = split_holdout(frames)
423
+ train_pool += [(fam, f) for f in tr]
424
+ held_pool += [(fam, f) for f in he]
425
+
426
+ # guard 2: no generator entity pair co-occurs in any probe v2/v3 context
427
+ gen_pairs = [(a, b) for _, pairs, *_ in COMPARATIVE for a, b in pairs] + [(o, c) for o, c, *_ in FIT]
428
+ overlap = [(a, b) for a, b in gen_pairs if any(f" {a.lower()} " in f" {c} " and f" {b.lower()} " in f" {c} " for c in probe_ctxs)]
429
+ assert not overlap, f"generator entity pairs co-occur in probe cases: {overlap}"
430
+
431
+ rng = random.Random(args.seed)
432
+ if args.dry_run:
433
+ for _ in range(args.dry_run):
434
+ print("-", document(rng, train_pool, train_names))
435
+ v4 = build_probe_v4(random.Random(args.seed + 1), held_pool, held_names)
436
+ print(f"[probe v4] {len(v4)} cases, e.g.:")
437
+ for c in v4[::25]:
438
+ print(" ", c["category"], "|", c["ctxA"], "->", c["c1"], "||", c["ctxB"], "->", c["c2"])
439
+ return
440
+
441
+ from transformers import AutoTokenizer
442
+ tok = AutoTokenizer.from_pretrained(args.tokenizer_path)
443
+ eot = tok.eos_token_id
444
+ out = Path(args.out_dir)
445
+ out.mkdir(parents=True, exist_ok=True)
446
+ buf = np.empty(args.shard_tokens, dtype=np.uint16)
447
+ pos, shard, total, unique, batch = 0, 0, 0, set(), []
448
+
449
+ def flush():
450
+ nonlocal pos, shard, total
451
+ for ids in tok(batch, add_special_tokens=False)["input_ids"]:
452
+ ids = ids + [eot]
453
+ if pos + len(ids) > args.shard_tokens:
454
+ buf[:pos].tofile(out / f"shard_{shard:05d}.bin"); shard += 1; pos = 0
455
+ buf[pos:pos + len(ids)] = ids
456
+ pos += len(ids); total += len(ids)
457
+ batch.clear()
458
+
459
+ for _ in range(args.n_docs):
460
+ doc = document(rng, train_pool, train_names)
461
+ if doc in unique:
462
+ continue
463
+ low = doc.lower()
464
+ bad = [b for b in BANNED_IN_TRAIN if b in low] # guard 3: no held-out / probe-v3 / v1 phrase
465
+ assert not bad, f"banned phrase {bad} in: {doc}"
466
+ unique.add(doc)
467
+ batch.append(doc)
468
+ if len(batch) >= 20_000:
469
+ flush()
470
+ if batch:
471
+ flush()
472
+ if pos:
473
+ buf[:pos].tofile(out / f"shard_{shard:05d}.bin"); shard += 1
474
+
475
+ meta = {"dataset": "synthetic_contrastive_binding_v2", "tokenizer_path": args.tokenizer_path, "total_tokens": total,
476
+ "n_docs": args.n_docs, "unique_docs": len(unique), "n_shards": shard, "dtype": "uint16", "eot_token": eot,
477
+ "real_vocab_size": len(tok), "is_code": False, "fim_rate": 0.0, "probe_exclusion_files": args.probe_files,
478
+ "train_frames": len(TRAIN_FRAMES), "heldout_frames": len(HELDOUT_FRAMES)}
479
+ (out / "meta.json").write_text(json.dumps(meta, indent=2))
480
+ print(json.dumps(meta, indent=2))
481
+
482
+ if args.probe_out:
483
+ cases = build_probe_v4(random.Random(args.seed + 1), held_pool, held_names)
484
+ Path(args.probe_out).write_text(json.dumps({
485
+ "description": "Probe v4: entity-attribute binding scored by log-likelihood, built ONLY from sentence frames, "
486
+ "entity pairs/relations and names held out of the contrastive v2 training corpus. Measures "
487
+ "template-free transfer of binding.",
488
+ "categories": sorted({c["category"] for c in cases}), "cases": cases}, indent=2))
489
+ print(f"[probe v4] wrote {len(cases)} cases to {args.probe_out}")
490
+
491
+
492
+ if __name__ == "__main__":
493
+ main()
v1/train-00000.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:611d652e5ad32a688b5e11b01485525193d7439b7f923c3cabb9fedb8df43858
3
+ size 11780555
v1/train-00001.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:70ae9084e06a7ac2dae987f0a97d13ad77248e67b17f31b971514c7fcced8eb1
3
+ size 11697283
v1/train-00002.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d1177b6193a9bff48e614ac5a01b7a0166c4c315cb29991c2f983a67b260b7dd
3
+ size 11713012
v1/train-00003.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:13340911b46c32f29be6a55780cdd67a53a73eca42cfd689da66bd249967a3af
3
+ size 11734877
v1/train-00004.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b01638bfcfcf877cc78cbedca1d0abb39112bfc43e2807b46fbf256d3f00916d
3
+ size 2129785
v2/train-00000.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:171980b923e3977d6e30b3296ebb03e1663d11adfa867741ccd5d3474ad7927c
3
+ size 16245272
v2/train-00001.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f1c69eef0c2ab60a05cc1d5199986768dc6eab9901ff03dae2e36e99a98b303
3
+ size 16410727
v2/train-00002.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cc6784966fbce775edb1316a9aeac3a9d57fe8224d189552419e105de46d161c
3
+ size 16450334
v2/train-00003.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:da7fa0571468d7e5cf2efd078c82d0fc65014229440f3e9212e9ffeeb8753d28
3
+ size 16485568
v2/train-00004.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4d1f9ecb93421056d1a8afa290007df82608ee00b4055eec49eab9efe96fb015
3
+ size 16515045
v2/train-00005.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:21abede59b5ad2f2db23b9a2ffb9df826ef263113a640fc334336b67767faa30
3
+ size 16536344
v2/train-00006.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:40ae1a3ab9b46021604b7f86671cabc9d181f101c969fc06f19caf1787566f9c
3
+ size 16548964
v2/train-00007.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fe89c7163b719e62369d711ea00d53ae7094687512c5f9533245b3805226102d
3
+ size 4483526