everydaytok commited on
Commit
f42e435
Β·
verified Β·
1 Parent(s): 697572b

Update data_gen.py

Browse files
Files changed (1) hide show
  1. data_gen.py +220 -51
data_gen.py CHANGED
@@ -1,74 +1,243 @@
1
  """
2
- data_gen.py v5
3
 
4
- Each sample: (A, B, C) where A,B,C ∈ ℝ^n, all values in [0.1, 0.9]
 
 
 
5
 
6
- For n=1 these are plain scalars.
7
- For n>1 each dimension is an independent weighted combination of A[i] and B[i],
8
- so the mesh must learn to route each channel correctly through the bulge.
9
 
10
- SEEN during training : heavy_a | avg | diff
11
- OOD (test only) : heavy_b ← has never been seen, tests geometric generalisation
 
 
 
 
 
 
 
 
 
 
 
 
12
  """
13
 
14
- import numpy as np, json, pathlib, random, argparse
15
- from collections import Counter
 
16
 
17
- N = 1 # embedding dimension (1 = pure scalar, set >1 for vector)
18
- SAMPLES_PER_TYPE = 2500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
- DATASETS = {
21
- 'heavy_a': (lambda a, b: 0.8*a + 0.2*b, True),
22
- 'avg': (lambda a, b: 0.5*a + 0.5*b, True),
23
- 'diff': (lambda a, b: 0.5 + 0.4*(a - b), True), # maps to [0.1, 0.9]
24
- 'heavy_b': (lambda a, b: 0.2*a + 0.8*b, False), # OOD
25
- }
26
 
27
- def generate(n=N, n_per=SAMPLES_PER_TYPE, seed=42):
28
- rng = np.random.default_rng(seed)
 
 
 
 
 
 
 
 
 
 
 
29
  data = []
30
- for dtype, (fn, _) in DATASETS.items():
31
- for _ in range(n_per):
32
- a = rng.uniform(0.1, 0.9, n).tolist()
33
- b = rng.uniform(0.1, 0.9, n).tolist()
34
- c = [round(float(fn(a[i], b[i])), 4) for i in range(n)]
35
- data.append({
36
- 'A': [round(v, 4) for v in a],
37
- 'B': [round(v, 4) for v in b],
38
- 'C': c,
39
- 'type': dtype,
40
- })
41
- random.shuffle(data)
42
  return data
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  if __name__ == '__main__':
45
- parser = argparse.ArgumentParser()
46
- parser.add_argument('--n', type=int, default=N, help='input dimensions')
47
- parser.add_argument('--spt', type=int, default=SAMPLES_PER_TYPE,help='samples per type')
48
- parser.add_argument('--out', type=str, default='data')
49
  args = parser.parse_args()
50
 
51
- data = generate(args.n, args.spt)
52
-
53
- seen = [d for d in data if DATASETS[d['type']][1]]
54
- ood = [d for d in data if not DATASETS[d['type']][1]]
55
 
56
- split = int(len(seen) * 0.9)
57
- train = seen[:split]
58
- test = seen[split:] + ood
59
- random.shuffle(test)
60
 
61
  out = pathlib.Path(args.out)
62
  out.mkdir(exist_ok=True)
63
  with open(out / 'train.json', 'w') as f: json.dump(train, f)
64
  with open(out / 'test.json', 'w') as f: json.dump(test, f)
65
 
66
- tr = Counter(d['type'] for d in train)
67
- te = Counter(d['type'] for d in test)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
- print(f"\n dim={args.n} total={len(data)}")
70
- print(f" {'Type':<12} {'Train':>7} {'Test':>7} Split")
71
- print(f" {'─'*12} {'─'*7} {'─'*7} {'─'*8}")
72
- for t, (_, seen_flag) in DATASETS.items():
73
- print(f" {t:<12} {tr.get(t,0):>7} {te.get(t,0):>7} {'SEEN' if seen_flag else 'OOD βœ—'}")
74
- print(f"\n β†’ {out}/train.json {out}/test.json\n")
 
1
  """
2
+ data_gen.py β€” Training / test data for the elastic mesh.
3
 
4
+ Each sample is a triple (A, B, C) where:
5
+ A ∈ ℝ^DIM encodes constraints ("what must be true")
6
+ B ∈ ℝ^DIM encodes objectives ("what we want")
7
+ C ∈ ℝ^DIM is the analytic solution β€” the feasibility center the mesh must learn to produce
8
 
9
+ Five problem families, each with a geometrically distinct C:
 
 
10
 
11
+ 1. box_proj β€” clamp B into axis-aligned box defined by A
12
+ 2. halfspace β€” project B onto hyperplane defined by A
13
+ 3. sphere β€” project B onto sphere surface defined by A
14
+ 4. simplex β€” project B onto probability simplex (A = uniform prior signal)
15
+ 5. elastic_bal β€” per-dimension weighted balance between A-center and B
16
+
17
+ These cover:
18
+ - Bounded feasibility (box)
19
+ - Equality constraints (halfspace)
20
+ - Norm constraints (sphere)
21
+ - Probability/sum=1 (simplex)
22
+ - Soft trade-offs (elastic)
23
+
24
+ The mesh sees ONLY (A, B) during inference; C is what it must reconstruct.
25
  """
26
 
27
+ import numpy as np
28
+ import json, pathlib, argparse
29
+ from typing import List, Dict
30
 
31
+ DIM = 32 # embedding dimension (set to 768 for LLM-scale)
32
+ SAMPLES_PER_TYPE = 1000 # Γ— 5 types = 5 000 total
33
+
34
+
35
+ # ── UTILITIES ─────────────────────────────────────────────────────────────────
36
+
37
+ def normalize(v: np.ndarray) -> np.ndarray:
38
+ n = np.linalg.norm(v)
39
+ return v / (n + 1e-12)
40
+
41
+ def pack(*arrays: np.ndarray, dim: int) -> np.ndarray:
42
+ """Concatenate + trim/pad to `dim`."""
43
+ v = np.concatenate(arrays)
44
+ if len(v) >= dim:
45
+ return v[:dim]
46
+ return np.pad(v, (0, dim - len(v)))
47
+
48
+
49
+ # ── PROBLEM TYPE 1: BOX PROJECTION ────────────────────────────────────────────
50
+ #
51
+ # Constraint A : encodes per-dimension box [lo, hi]
52
+ # A[:D/2] = lo[:D/2], A[D/2:] = hi[:D/2]
53
+ # Objective B : unconstrained target point in ℝ^D
54
+ # Solution C : clip(B, lo, hi) β€” nearest point in box to B
55
+ #
56
+ # Meaning: "stay within resource/capacity bounds while aiming for B"
57
+
58
+ def gen_box(n: int, dim: int, rng: np.random.Generator) -> List[Dict]:
59
+ data = []
60
+ for _ in range(n):
61
+ center = rng.uniform(-2, 2, dim)
62
+ half = rng.uniform(0.3, 2.0, dim)
63
+ lo, hi = center - half, center + half
64
+ B = rng.uniform(-4, 4, dim)
65
+ C = np.clip(B, lo, hi)
66
+ A = pack(lo[:dim//2], hi[:dim//2], dim=dim)
67
+ data.append({'A': A.tolist(), 'B': B.tolist(), 'C': C.tolist(), 'type': 'box_proj'})
68
+ return data
69
+
70
+
71
+ # ── PROBLEM TYPE 2: HALFSPACE PROJECTION ──────────────────────────────────────
72
+ #
73
+ # Constraint A : encodes a hyperplane nα΅€x = b
74
+ # A = normal vector, A[0] carries the offset b
75
+ # Objective B : unconstrained point in ℝ^D
76
+ # Solution C : projection of B onto the hyperplane
77
+ # C = B βˆ’ (nα΅€B βˆ’ b) Β· n
78
+ #
79
+ # Meaning: "satisfy one hard equality constraint at minimum cost to B"
80
+
81
+ def gen_halfspace(n: int, dim: int, rng: np.random.Generator) -> List[Dict]:
82
+ data = []
83
+ for _ in range(n):
84
+ normal = normalize(rng.standard_normal(dim))
85
+ b = float(rng.uniform(-1, 1))
86
+ B = rng.uniform(-3, 3, dim)
87
+ C = B - (float(np.dot(normal, B)) - b) * normal
88
+ A = normal.copy()
89
+ A[0] = b # offset embedded in first slot
90
+ data.append({'A': A.tolist(), 'B': B.tolist(), 'C': C.tolist(), 'type': 'halfspace'})
91
+ return data
92
+
93
+
94
+ # ── PROBLEM TYPE 3: SPHERE SURFACE ────────────────────────────────────────────
95
+ #
96
+ # Constraint A : encodes a sphere (center, radius)
97
+ # A = center vector, A[0] overwritten with radius r
98
+ # Objective B : external point
99
+ # Solution C : point on sphere surface nearest to B
100
+ # C = center + r Β· (B βˆ’ center) / β€–B βˆ’ centerβ€–
101
+ #
102
+ # Meaning: "satisfy a norm/budget constraint, move toward B as far as allowed"
103
+
104
+ def gen_sphere(n: int, dim: int, rng: np.random.Generator) -> List[Dict]:
105
+ data = []
106
+ for _ in range(n):
107
+ center = rng.uniform(-1.5, 1.5, dim)
108
+ r = float(rng.uniform(1.0, 3.0))
109
+ B = rng.uniform(-4, 4, dim)
110
+ diff = B - center
111
+ nd = np.linalg.norm(diff)
112
+ if nd < 1e-10:
113
+ diff = np.ones(dim) / np.sqrt(dim)
114
+ nd = 1.0
115
+ C = center + r * diff / nd
116
+ A = center.copy()
117
+ A[0] = r # radius in first slot
118
+ data.append({'A': A.tolist(), 'B': B.tolist(), 'C': C.tolist(), 'type': 'sphere'})
119
+ return data
120
+
121
+
122
+ # ── PROBLEM TYPE 4: SIMPLEX PROJECTION ────────────────────────────────────────
123
+ #
124
+ # Constraint A : uniform-prior signal (all ones) β†’ encodes simplex constraint Ξ£xα΅’=1, xα΅’β‰₯0
125
+ # Objective B : unconstrained "belief" vector
126
+ # Solution C : nearest point on probability simplex to B
127
+ #
128
+ # Meaning: "find a valid probability distribution closest to unconstrained belief B"
129
+ # Useful for softmax-like problems.
130
+
131
+ def _proj_simplex(v: np.ndarray) -> np.ndarray:
132
+ n = len(v)
133
+ u = np.sort(v)[::-1]
134
+ cs = np.cumsum(u) - 1.0
135
+ rho = int(np.where(u * np.arange(1, n + 1) > cs)[0][-1])
136
+ theta = cs[rho] / (rho + 1.0)
137
+ return np.maximum(v - theta, 0.0)
138
+
139
+ def gen_simplex(n: int, dim: int, rng: np.random.Generator) -> List[Dict]:
140
+ data = []
141
+ for _ in range(n):
142
+ A = np.ones(dim) # simplex constraint signal
143
+ B = rng.uniform(-1.0, 3.0, dim) # unconstrained belief
144
+ C = _proj_simplex(B)
145
+ data.append({'A': A.tolist(), 'B': B.tolist(), 'C': C.tolist(), 'type': 'simplex'})
146
+ return data
147
 
 
 
 
 
 
 
148
 
149
+ # ── PROBLEM TYPE 5: ELASTIC BALANCE ───────────────────────────────────────────
150
+ #
151
+ # Constraint A : encodes soft constraint center + per-dimension tightness weight w ∈ [0,1]
152
+ # A[:D/2] = constraint centers, A[D/2:] = tightness weights
153
+ # Objective B : desired goal point
154
+ # Solution C : per-dimension elastic balance
155
+ # C[j] = w[j] Β· a_center[j] + (1 βˆ’ w[j]) Β· B[j]
156
+ #
157
+ # Meaning: "each dimension is pulled between constraint center and objective,
158
+ # with w[j] controlling how hard the constraint is in that dimension"
159
+ # This is the natural problem for the elastic mesh.
160
+
161
+ def gen_elastic(n: int, dim: int, rng: np.random.Generator) -> List[Dict]:
162
  data = []
163
+ for _ in range(n):
164
+ a_center = rng.uniform(-2, 2, dim)
165
+ w = rng.uniform(0.05, 0.95, dim) # per-dim tightness
166
+ B = rng.uniform(-3, 3, dim)
167
+ C = w * a_center + (1.0 - w) * B
168
+ A = pack(a_center[:dim//2], w[:dim//2], dim=dim)
169
+ data.append({'A': A.tolist(), 'B': B.tolist(), 'C': C.tolist(), 'type': 'elastic'})
 
 
 
 
 
170
  return data
171
 
172
+
173
+ # ── ASSEMBLY ──────────────────────────────────────────────────────────────────
174
+
175
+ GENERATORS = {
176
+ 'box_proj': gen_box,
177
+ 'halfspace': gen_halfspace,
178
+ 'sphere': gen_sphere,
179
+ 'simplex': gen_simplex,
180
+ 'elastic': gen_elastic,
181
+ }
182
+
183
+ def generate_all(n_per_type: int = SAMPLES_PER_TYPE,
184
+ dim: int = DIM,
185
+ seed: int = 42) -> List[Dict]:
186
+ rng = np.random.default_rng(seed)
187
+ data = []
188
+ for fn in GENERATORS.values():
189
+ data.extend(fn(n_per_type, dim, rng))
190
+ idx = rng.permutation(len(data))
191
+ return [data[i] for i in idx]
192
+
193
+
194
+ # ── MAIN ──────────────────────────────────────────────────────────────────────
195
+
196
  if __name__ == '__main__':
197
+ parser = argparse.ArgumentParser(description='Generate elastic mesh training data')
198
+ parser.add_argument('--dim', type=int, default=DIM, help='embedding dimension')
199
+ parser.add_argument('--n', type=int, default=SAMPLES_PER_TYPE, help='samples per problem type')
200
+ parser.add_argument('--out', type=str, default='data', help='output directory')
201
  args = parser.parse_args()
202
 
203
+ print(f"\n{'─'*50}")
204
+ print(f" Generating {5 * args.n} samples | dim={args.dim}")
205
+ print(f"{'─'*50}")
 
206
 
207
+ data = generate_all(args.n, args.dim)
208
+ split = int(len(data) * 0.9)
209
+ train, test = data[:split], data[split:]
 
210
 
211
  out = pathlib.Path(args.out)
212
  out.mkdir(exist_ok=True)
213
  with open(out / 'train.json', 'w') as f: json.dump(train, f)
214
  with open(out / 'test.json', 'w') as f: json.dump(test, f)
215
 
216
+ # Per-type statistics
217
+ from collections import Counter
218
+ train_types = Counter(d['type'] for d in train)
219
+ test_types = Counter(d['type'] for d in test)
220
+
221
+ print(f"\n Train : {len(train)}")
222
+ print(f" Test : {len(test)}\n")
223
+ print(f" {'Type':<14} {'Train':>8} {'Test':>7} C-norm (mean)")
224
+ print(f" {'─'*14} {'─'*8} {'─'*7} {'─'*14}")
225
+ for t in GENERATORS:
226
+ subset = [d for d in data if d['type'] == t]
227
+ norms = [np.linalg.norm(d['C']) for d in subset]
228
+ print(f" {t:<14} {train_types[t]:>8} {test_types[t]:>7} "
229
+ f"{np.mean(norms):.3f} Β± {np.std(norms):.3f}")
230
+
231
+ # Sanity check one sample per type
232
+ print(f"\n Sanity check (first sample per type):")
233
+ seen = set()
234
+ for d in data:
235
+ if d['type'] in seen: continue
236
+ seen.add(d['type'])
237
+ A, B, C = map(np.array, [d['A'], d['B'], d['C']])
238
+ err = np.linalg.norm(A - B)
239
+ print(f" [{d['type']:<12}] "
240
+ f"β€–Aβ€–={np.linalg.norm(A):.2f} β€–Bβ€–={np.linalg.norm(B):.2f} "
241
+ f"β€–Cβ€–={np.linalg.norm(C):.2f} β€–A-Bβ€–={err:.2f}")
242
 
243
+ print(f"\n Saved β†’ {out}/train.json {out}/test.json\n")