unparallelled commited on
Commit
2ff33ec
·
verified ·
1 Parent(s): 0be0229

Upload source/files/in2_gen.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. source/files/in2_gen.py +316 -0
source/files/in2_gen.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ in2_gen.py -- synthesise IN2-style TRAINING shards for bluscriptCP.
4
+
5
+ IN2 (arXiv:2404.16811) teaches long-range retrieval by making the answer
6
+ impossible to produce without a fact planted at a random distant position. We
7
+ cannot reproduce its "loss on the answer only" masking (see the plan: TI has no
8
+ maskable CE, `narrow` has no autograd node, and sentinel target ids are unsafe
9
+ because the fwd/bwd kernels do not bounds-check). So we remove the NEED to mask:
10
+
11
+ * our filler is CONTIGUOUS REAL TEXT, not IN2's shuffled-segment bag, so
12
+ unmasked LM loss on it is ordinary harmless LM training; and
13
+ * dilution is fixed by construction -- K triples per example raise the answer
14
+ tokens from ~0.1% of positions to several percent.
15
+
16
+ Output is what DataLoaderLite already eats: a HEADERLESS little-endian uint16
17
+ token stream in a file whose name contains "train"/"val", under a directory
18
+ passed as CP_DATA_ROOT. No C++ training/loss/loader change is required.
19
+
20
+ LAYOUT (one example = exactly T tokens)
21
+
22
+ [ filler, with needles and decoys planted throughout ]
23
+ ^needle_i (key_i + val_i) ^decoy (key + val, NO probe)
24
+ ... and at each site p_i: [ key_i ][ val_i ]
25
+ probe answer
26
+
27
+ * SITES p_i are drawn from an ARM-INDEPENDENT rng stream, so arms B and C have
28
+ bit-identical answer-position histograms and differ ONLY in needle distance.
29
+ Without this we would difference NLLs measured at different points on a
30
+ position-varying curve -- the error needle_gen.py's fixed-slot design exists
31
+ to prevent.
32
+ * Sites are INTERLEAVED over the sequence, never concatenated at the tail:
33
+ tail-packing would confine every supervised position to the last K*SPAN
34
+ offsets and train a position-specific circuit indistinguishable from
35
+ retrieval.
36
+ * PAIRING is shuffled and DECOY needles (no probe) are planted, so "the i-th
37
+ probe pairs with the i-th needle" is not a winning heuristic. That shortcut
38
+ is order/counting, not content retrieval, and would earn full reward at any
39
+ distance.
40
+ * KEY ALPHABET is capped (default 512, not the full 50304). Uniform draws from
41
+ the vocab cost ln(50304)=10.83 nats IRREDUCIBLY -- pure noise that inflates
42
+ the pre-clip gradient norm and, against the GLOBAL clip_grad_norm_(1.0),
43
+ could silently leave the arms not LR-matched. ln(512)=6.24 nats gives the
44
+ same discriminability (512^4 = 6.9e10 keys) with 42% less noise.
45
+
46
+ ARMS
47
+ a plain text, no injection -- drift control
48
+ b needle immediately before its probe -- the objective change at distance ~0
49
+ c needle uniform in [0, p_i - SPAN) -- DISTANCE, the actual IN2 claim
50
+
51
+ Stdlib only, matching needle_gen.py (the local pyenv python3 lacks numpy).
52
+
53
+ Usage
54
+ python3 in2_gen.py --arm c --T 16384 --examples 64 --split train --out-dir /tmp/in2c
55
+ python3 in2_gen.py --arm b --T 16384 --examples 64 --split train --out-dir /tmp/in2b
56
+ """
57
+ import argparse, array, json, os, random, sys
58
+
59
+ VOCAB = 50304 # must match cfg.vocab_size; the C++ side bound-checks too
60
+ PAD_TAIL = 4 # >=2: the loader's y-shift makes the last position of each
61
+ # example target the NEXT example's first token. Keep the
62
+ # answer clear of it.
63
+ MIX = 1_000_003 # odd multiplier for deterministic seed derivation
64
+ MAX_SHARD_TOKENS = 100_000_000 # DataLoaderLite is constructed with this cap;
65
+ # anything past it in a shard is SILENTLY invisible
66
+
67
+
68
+ def check_platform():
69
+ if sys.byteorder != "little":
70
+ raise SystemExit("training shards must be uint16 LITTLE-endian; this host is big-endian")
71
+ if array.array("H").itemsize != 2:
72
+ raise SystemExit("unexpected array itemsize ('H' must be 2B)")
73
+
74
+
75
+ def load_filler(path, need, rng):
76
+ """One CONTIGUOUS run of real tokens per example, so filler keeps local
77
+ textual statistics. Source shards are already uint16, so unlike
78
+ needle_gen.py (which must widen to int32 for CP_EVAL_TOKENS_BIN) we keep the
79
+ native width -- training shards are uint16."""
80
+ ntok = os.path.getsize(path) // 2
81
+ if ntok < need + 1:
82
+ raise SystemExit(f"{path} has {ntok} tokens, need >= {need + 1}")
83
+ start = rng.randrange(0, ntok - need)
84
+ buf = array.array("H")
85
+ with open(path, "rb") as f:
86
+ f.seek(start * 2)
87
+ buf.fromfile(f, need)
88
+ lo, hi = min(buf), max(buf)
89
+ if lo < 0 or hi >= VOCAB:
90
+ raise SystemExit(f"{path} has ids outside [0,{VOCAB}): min={lo} max={hi}")
91
+ return buf
92
+
93
+
94
+ def draw_sites(T, n, span, rng, lo_margin):
95
+ """n site starts in [lo_margin, T-PAD_TAIL-span], separated by >= 2*span.
96
+
97
+ Drawn from an ARM-INDEPENDENT rng so every arm sees the same sites. Returned
98
+ sorted; the pairing to needles is shuffled separately.
99
+
100
+ Separation is 2*span, not span, and the reason is load-bearing: arm B plants
101
+ its needle immediately before the probe, at p-span. At only span separation,
102
+ two adjacent sites can sit exactly span apart and B's needle then lands on
103
+ top of the earlier site, so B silently drops that triple -- which would make
104
+ B's answer_start histogram DIFFER from C's and destroy the matched-position
105
+ discipline the B-vs-C contrast depends on. The constraint is applied for all
106
+ arms so sites stay arm-independent.
107
+ """
108
+ hi = T - PAD_TAIL - span
109
+ if hi <= lo_margin:
110
+ raise SystemExit(f"T={T} too small for span={span}")
111
+ sep = 2 * span
112
+ chosen = []
113
+ guard = 0
114
+ while len(chosen) < n:
115
+ guard += 1
116
+ if guard > 400 * n:
117
+ raise SystemExit(f"could not place {n} sites in T={T} at separation {sep}; "
118
+ f"lower --K (need roughly K*{sep} << {hi - lo_margin})")
119
+ p = rng.randrange(lo_margin, hi + 1)
120
+ if all(abs(p - q) >= sep for q in chosen):
121
+ chosen.append(p)
122
+ return sorted(chosen)
123
+
124
+
125
+ def place_free(occupied, T, span, rng, hi_bound):
126
+ """A start in [0, hi_bound-span] disjoint from `occupied`; None if it fails."""
127
+ for _ in range(400):
128
+ if hi_bound - span < 0:
129
+ return None
130
+ s = rng.randrange(0, hi_bound - span + 1)
131
+ if all(s + span <= a or s >= a + span for a, _ in occupied):
132
+ return s
133
+ return None
134
+
135
+
136
+ def make_example(arm, T, K, key_len, val_len, alphabet, decoys, d_min,
137
+ filler, site_rng, arm_rng):
138
+ """Returns (tokens uint16 array of length T, list of records).
139
+
140
+ site_rng -- ARM-INDEPENDENT: sites, keys, values, pairing.
141
+ arm_rng -- arm-specific: needle placement only.
142
+ """
143
+ span = key_len + val_len
144
+ toks = filler # fresh copy per example
145
+ recs = []
146
+
147
+ if arm == "a": # plain text, no injection
148
+ return toks, recs, 0
149
+
150
+ sites = draw_sites(T, K, span, site_rng, lo_margin=span + d_min)
151
+
152
+ # Distinct key/value pairs, then a shuffled site<->needle pairing so the
153
+ # i-th probe does not correspond to the i-th needle by position.
154
+ keys = [[site_rng.randrange(alphabet) for _ in range(key_len)] for _ in range(K)]
155
+ vals = [[site_rng.randrange(alphabet) for _ in range(val_len)] for _ in range(K)]
156
+ order = list(range(K))
157
+ site_rng.shuffle(order)
158
+
159
+ occupied = [(p, "site") for p in sites]
160
+
161
+ for si, p in enumerate(sites):
162
+ j = order[si] # which key/value this site queries
163
+ key, val = keys[j], vals[j]
164
+ toks[p:p + key_len] = array.array("H", key) # probe
165
+ toks[p + key_len:p + span] = array.array("H", val) # answer
166
+
167
+ if arm == "b":
168
+ ns = p - span # immediately before the probe
169
+ # Guaranteed free by the 2*span site separation; assert rather than
170
+ # skip, because a silent skip would desynchronise B's histogram from C's.
171
+ if ns < 0 or any(ns + span > a and ns < a + span
172
+ for a, _ in occupied if a != p):
173
+ raise SystemExit(f"arm b: needle slot {ns} for site {p} is occupied -- "
174
+ "site separation invariant violated")
175
+ else: # arm c: uniform, far
176
+ hi = p - d_min
177
+ ns = place_free(occupied, T, span, arm_rng, hi)
178
+ if ns is None:
179
+ raise SystemExit(f"arm c: could not place a needle before site {p} "
180
+ f"(d_min={d_min}); lower --K or --d-min")
181
+ toks[ns:ns + span] = array.array("H", key + val)
182
+ occupied.append((ns, "needle"))
183
+
184
+ answer_start = p + key_len
185
+ recs.append(dict(needle_start=ns, probe_start=p, answer_start=answer_start,
186
+ distance=p - ns,
187
+ csv_first=answer_start - 1)) # see off-by-one note below
188
+
189
+ n_decoy = 0
190
+ # Decoy needles: no probe queries them, so needle count != probe count and
191
+ # the i-th-of-K index carries no information.
192
+ for _ in range(decoys):
193
+ key = [site_rng.randrange(alphabet) for _ in range(key_len)]
194
+ val = [site_rng.randrange(alphabet) for _ in range(val_len)]
195
+ ds = place_free(occupied, T, span, arm_rng, T - PAD_TAIL)
196
+ if ds is None:
197
+ continue
198
+ toks[ds:ds + span] = array.array("H", key + val)
199
+ occupied.append((ds, "decoy"))
200
+ n_decoy += 1
201
+
202
+ return toks, recs, n_decoy
203
+
204
+
205
+ def main():
206
+ ap = argparse.ArgumentParser()
207
+ ap.add_argument("--arm", required=True, choices=["a", "b", "c"])
208
+ ap.add_argument("--T", type=int, required=True)
209
+ ap.add_argument("--examples", type=int, required=True)
210
+ ap.add_argument("--split", default="train", choices=["train", "val"])
211
+ ap.add_argument("--K", type=int, default=64, help="triples per example")
212
+ ap.add_argument("--key-len", type=int, default=4, help="probe/key tokens")
213
+ ap.add_argument("--val-len", type=int, default=8, help="answer/value tokens")
214
+ ap.add_argument("--alphabet", type=int, default=512, help="key/value alphabet size")
215
+ ap.add_argument("--decoys", type=int, default=None, help="default K//4")
216
+ ap.add_argument("--d-min", type=int, default=64, help="arm c: min needle->probe distance")
217
+ ap.add_argument("--filler-shards", nargs="+", required=True)
218
+ ap.add_argument("--seed", type=int, default=0)
219
+ ap.add_argument("--out-dir", required=True)
220
+ ap.add_argument("--shards", type=int, default=1,
221
+ help="split the examples across this many files. REQUIRED above "
222
+ "100M tokens: DataLoaderLite is constructed with a "
223
+ "max_tokens_per_shard of 1e8 and anything past it in a single "
224
+ "shard is SILENTLY invisible. The example index stays GLOBAL "
225
+ "across shards, so the arm-independent RNG stream (sites, keys, "
226
+ "pairing, filler) is unchanged by how the split falls -- arms "
227
+ "remain comparable.")
228
+ args = ap.parse_args()
229
+
230
+ check_platform()
231
+ if args.alphabet > VOCAB:
232
+ raise SystemExit(f"--alphabet {args.alphabet} exceeds VOCAB {VOCAB}")
233
+ decoys = args.decoys if args.decoys is not None else args.K // 4
234
+ span = args.key_len + args.val_len
235
+ for f in args.filler_shards:
236
+ if not os.path.exists(f):
237
+ raise SystemExit(f"filler shard not found: {f}")
238
+ if args.split == "train" and "val" in os.path.basename(f):
239
+ raise SystemExit(f"refusing to build TRAIN data from a val shard: {f}\n"
240
+ " eval filler must stay disjoint from training data")
241
+ os.makedirs(args.out_dir, exist_ok=True)
242
+
243
+ total_tok = args.examples * args.T
244
+ per_shard = (args.examples + args.shards - 1) // args.shards
245
+ if per_shard * args.T > MAX_SHARD_TOKENS:
246
+ raise SystemExit(f"{per_shard * args.T} tokens/shard exceeds the loader's "
247
+ f"{MAX_SHARD_TOKENS} cap; raise --shards to at least "
248
+ f"{(total_tok + MAX_SHARD_TOKENS - 1) // MAX_SHARD_TOKENS}")
249
+
250
+ all_recs, hist, n_decoy_total = [], {}, 0
251
+ shard_paths = []
252
+ stream = array.array("H")
253
+ shard_i = 0
254
+ for i in range(args.examples):
255
+ # Site/key/value/pairing rng is ARM-INDEPENDENT -- identical across arms.
256
+ site_rng = random.Random(((args.seed * MIX + args.T) * MIX + i) * MIX + 7)
257
+ # Needle placement is arm-specific.
258
+ arm_rng = random.Random(((args.seed * MIX + args.T) * MIX + i) * MIX
259
+ + 1000 + ord(args.arm))
260
+ # Filler draw is arm-independent too, so arms see the same documents.
261
+ fill_rng = random.Random(((args.seed * MIX + args.T) * MIX + i) * MIX + 99)
262
+ shard = args.filler_shards[i % len(args.filler_shards)]
263
+ filler = load_filler(shard, args.T, fill_rng)
264
+
265
+ toks, recs, n_dec = make_example(args.arm, args.T, args.K, args.key_len, args.val_len,
266
+ args.alphabet, decoys, args.d_min,
267
+ filler, site_rng, arm_rng)
268
+ if len(toks) != args.T:
269
+ raise SystemExit(f"example {i} is {len(toks)} tokens, expected {args.T}")
270
+ stream.extend(toks)
271
+ for r in recs:
272
+ hist[r["answer_start"]] = hist.get(r["answer_start"], 0) + 1
273
+ all_recs.append(recs)
274
+ n_decoy_total += n_dec
275
+
276
+ # Flush a shard whenever it is full, or on the last example. The global `i`
277
+ # above drives every RNG, so the split point cannot change the data.
278
+ if len(stream) // args.T >= per_shard or i == args.examples - 1:
279
+ sp = os.path.join(args.out_dir, f"in2{args.arm}_{args.split}_{shard_i:05d}.bin")
280
+ with open(sp, "wb") as f:
281
+ stream.tofile(f)
282
+ shard_paths.append(sp)
283
+ stream = array.array("H")
284
+ shard_i += 1
285
+
286
+ path = shard_paths[0]
287
+
288
+ n_ans = sum(len(r) for r in all_recs) * args.val_len
289
+ # Counted from ACTUAL placements, never derived from parameters: arm A plants
290
+ # nothing, so a parameter-derived figure reported phantom decoy tokens for it.
291
+ n_syn = sum(len(r) for r in all_recs) * (2 * span) + n_decoy_total * span
292
+ man = dict(arm=args.arm, T=args.T, examples=args.examples, split=args.split,
293
+ K=args.K, key_len=args.key_len, val_len=args.val_len, span=span,
294
+ alphabet=args.alphabet, decoys=decoys, d_min=args.d_min,
295
+ seed=args.seed, vocab=VOCAB, pad_tail=PAD_TAIL,
296
+ filler_shards=args.filler_shards, bin=path, shards=shard_paths,
297
+ total_tokens=total_tok, dtype="uint16",
298
+ answer_tokens=n_ans, answer_frac=n_ans / total_tok,
299
+ synthetic_tokens=n_syn, synthetic_frac=n_syn / total_tok,
300
+ decoys_placed=n_decoy_total,
301
+ answer_start_hist=dict(sorted(hist.items())),
302
+ records=all_recs)
303
+ with open(path.replace(".bin", ".json"), "w") as f:
304
+ json.dump(man, f, indent=1)
305
+
306
+ print(f"wrote {len(shard_paths)} shard(s) in {args.out_dir} {total_tok} tokens total")
307
+ print(f" answer tokens {n_ans} ({n_ans/total_tok:.2%}) "
308
+ f"synthetic {n_syn} ({n_syn/total_tok:.2%})")
309
+ if all_recs and all_recs[0]:
310
+ ds = [r["distance"] for rs in all_recs for r in rs]
311
+ ds.sort()
312
+ print(f" distance: min {ds[0]} median {ds[len(ds)//2]} max {ds[-1]} n={len(ds)}")
313
+
314
+
315
+ if __name__ == "__main__":
316
+ main()