anhtld commited on
Commit
f4ef5ef
·
verified ·
1 Parent(s): a67a297

manual-sync 2026-07-02T20:50:21Z local-atlas-guided-flow dovla_cil/generation

Browse files
workspace/dovla_cil/generation/tangent_local_atlas.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from collections import Counter
5
+ from collections.abc import Sequence
6
+ from dataclasses import asdict, dataclass
7
+ from typing import Any
8
+
9
+ from dovla_cil.generation.tangent_spline_cvae import (
10
+ SplineTangentRow,
11
+ _aggregate_rows,
12
+ _evaluate_generated_group,
13
+ _split_rows,
14
+ _validate_eval_args,
15
+ build_spline_tangent_rows,
16
+ )
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class LocalAtlasConfig:
21
+ obs_dim: int = 96
22
+ text_dim: int = 64
23
+ val_fraction: float = 0.2
24
+ seed: int = 0
25
+ neighbor_pool: int = 16
26
+ utility_weight: float = 0.0
27
+ diversity_weight: float = 0.0
28
+ same_task_only: bool = True
29
+
30
+ def __post_init__(self) -> None:
31
+ if self.obs_dim <= 0:
32
+ raise ValueError("obs_dim must be positive")
33
+ if self.text_dim <= 0:
34
+ raise ValueError("text_dim must be positive")
35
+ if not 0.0 < self.val_fraction < 1.0:
36
+ raise ValueError("val_fraction must be in (0, 1)")
37
+ if self.neighbor_pool <= 0:
38
+ raise ValueError("neighbor_pool must be positive")
39
+ if self.utility_weight < 0:
40
+ raise ValueError("utility_weight must be non-negative")
41
+ if self.diversity_weight < 0:
42
+ raise ValueError("diversity_weight must be non-negative")
43
+
44
+
45
+ def evaluate_local_atlas_retrieval(
46
+ targets: Sequence[dict[str, Any]],
47
+ *,
48
+ config: LocalAtlasConfig | None = None,
49
+ k_values: Sequence[int] = (1, 2, 4, 8, 16),
50
+ thresholds: Sequence[float] = (0.05, 0.1, 0.2, 0.4),
51
+ ) -> dict[str, Any]:
52
+ config = config or LocalAtlasConfig()
53
+ _validate_eval_args(k_values, thresholds)
54
+ rows, task_ids, code_dim, horizon, action_dim = build_spline_tangent_rows(
55
+ targets,
56
+ obs_dim=config.obs_dim,
57
+ text_dim=config.text_dim,
58
+ )
59
+ if not rows:
60
+ raise ValueError("no usable spline tangent rows")
61
+ split = _split_rows(rows, val_fraction=config.val_fraction, seed=config.seed)
62
+ train_positive = [
63
+ row for row in split["train"]
64
+ if row.example.tangent_label == "positive"
65
+ ]
66
+ if not train_positive:
67
+ raise ValueError("no train positive tangents")
68
+ train_positive_by_task: dict[str, list[SplineTangentRow]] = {}
69
+ for row in train_positive:
70
+ train_positive_by_task.setdefault(row.example.task_id, []).append(row)
71
+
72
+ max_k = max(int(k) for k in k_values)
73
+ val_by_group: dict[str, list[SplineTangentRow]] = {}
74
+ for row in split["val"]:
75
+ val_by_group.setdefault(row.example.group_id, []).append(row)
76
+
77
+ groups: list[dict[str, Any]] = []
78
+ for group_id, group_rows in sorted(val_by_group.items()):
79
+ positives = [
80
+ row.example for row in group_rows
81
+ if row.example.tangent_label == "positive"
82
+ ]
83
+ if not positives:
84
+ continue
85
+ negatives = [
86
+ row.example for row in group_rows
87
+ if row.example.tangent_label == "negative"
88
+ ]
89
+ selected = _select_local_positive_tangents(
90
+ group_rows[0],
91
+ train_positive=train_positive,
92
+ train_positive_by_task=train_positive_by_task,
93
+ config=config,
94
+ max_k=max_k,
95
+ )
96
+ groups.append(
97
+ _evaluate_generated_group(
98
+ group_id,
99
+ task_id=group_rows[0].example.task_id,
100
+ proposals=[_flat_delta(row) for row in selected],
101
+ positives=positives,
102
+ negatives=negatives,
103
+ k_values=k_values,
104
+ thresholds=thresholds,
105
+ )
106
+ )
107
+
108
+ return {
109
+ "report_type": "positive_tangent_local_atlas_retrieval_eval",
110
+ "metric_scope": "offline_support_proxy",
111
+ "note": (
112
+ "Local-atlas retrieval proposes train-only positive tangents from "
113
+ "nearest observation-language-task chart neighborhoods. It is a "
114
+ "diagnostic upper baseline for local support reuse, not a deployment "
115
+ "claim that same-state outcomes are available."
116
+ ),
117
+ "config": asdict(config),
118
+ "task_ids": list(task_ids),
119
+ "code_dim": code_dim,
120
+ "horizon": horizon,
121
+ "action_dim": action_dim,
122
+ "num_examples": len(rows),
123
+ "num_groups": len({row.example.group_id for row in rows}),
124
+ "num_train_examples": len(split["train"]),
125
+ "num_val_examples": len(split["val"]),
126
+ "num_train_positive": len(train_positive),
127
+ "num_val_groups_with_positive": len(groups),
128
+ "label_counts": dict(Counter(row.example.tangent_label for row in rows)),
129
+ "train_positive_by_task": {
130
+ task_id: len(train_positive_by_task.get(task_id, []))
131
+ for task_id in task_ids
132
+ },
133
+ "overall": _aggregate_rows(groups, k_values=k_values, thresholds=thresholds),
134
+ "per_task": {
135
+ task_id: _aggregate_rows(
136
+ [group for group in groups if group["task_id"] == task_id],
137
+ k_values=k_values,
138
+ thresholds=thresholds,
139
+ )
140
+ for task_id in task_ids
141
+ },
142
+ "groups": groups,
143
+ }
144
+
145
+
146
+ def _select_local_positive_tangents(
147
+ query: SplineTangentRow,
148
+ *,
149
+ train_positive: Sequence[SplineTangentRow],
150
+ train_positive_by_task: dict[str, list[SplineTangentRow]],
151
+ config: LocalAtlasConfig,
152
+ max_k: int,
153
+ ) -> list[SplineTangentRow]:
154
+ if config.same_task_only:
155
+ pool = train_positive_by_task.get(query.example.task_id, []) or list(train_positive)
156
+ else:
157
+ pool = list(train_positive)
158
+ ranked = sorted(
159
+ (
160
+ (_condition_distance(query.condition, row.condition), row)
161
+ for row in pool
162
+ ),
163
+ key=lambda item: (item[0], -item[1].example.delta_utility, item[1].example.group_id),
164
+ )
165
+ candidates = ranked[: max(int(config.neighbor_pool), max_k)]
166
+ selected: list[tuple[float, SplineTangentRow]] = []
167
+ remaining = list(candidates)
168
+ while remaining and len(selected) < max_k:
169
+ if not selected:
170
+ chosen = remaining[0]
171
+ else:
172
+ chosen = max(
173
+ remaining,
174
+ key=lambda item: (
175
+ -item[0]
176
+ + float(config.utility_weight) * item[1].example.delta_utility
177
+ + float(config.diversity_weight)
178
+ * _nearest_action_distance(item[1], [row for _, row in selected]),
179
+ item[1].example.delta_utility,
180
+ ),
181
+ )
182
+ selected.append(chosen)
183
+ remaining = [item for item in remaining if item is not chosen]
184
+ return [row for _, row in selected]
185
+
186
+
187
+ def _condition_distance(left: Sequence[float], right: Sequence[float]) -> float:
188
+ return _rms_distance(left, right)
189
+
190
+
191
+ def _nearest_action_distance(
192
+ row: SplineTangentRow,
193
+ selected: Sequence[SplineTangentRow],
194
+ ) -> float:
195
+ if not selected:
196
+ return 0.0
197
+ values = _flat_delta(row)
198
+ return min(_rms_distance(values, _flat_delta(other)) for other in selected)
199
+
200
+
201
+ def _flat_delta(row: SplineTangentRow) -> list[float]:
202
+ return row.example.flat_delta
203
+
204
+
205
+ def _rms_distance(left: Sequence[float], right: Sequence[float]) -> float:
206
+ size = min(len(left), len(right))
207
+ if size <= 0:
208
+ return 0.0
209
+ return math.sqrt(
210
+ sum((float(left[index]) - float(right[index])) ** 2 for index in range(size))
211
+ / size
212
+ )
workspace/dovla_cil/generation/tangent_spline_cvae.py ADDED
@@ -0,0 +1,618 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import math
5
+ from collections import Counter, defaultdict
6
+ from collections.abc import Sequence
7
+ from dataclasses import asdict, dataclass
8
+ from typing import Any
9
+
10
+ from dovla_cil.generation.tangent_cvae import (
11
+ PositiveTangentCVAE,
12
+ TangentCVAEConfig,
13
+ condition_vector,
14
+ )
15
+ from dovla_cil.generation.tangent_memory import TangentExample
16
+
17
+ try:
18
+ import torch
19
+ from torch.utils.data import DataLoader, TensorDataset
20
+ except ImportError: # pragma: no cover - login shells may not have torch
21
+ torch = None
22
+ DataLoader = None
23
+ TensorDataset = None
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class SplineTangentRow:
28
+ example: TangentExample
29
+ condition: list[float]
30
+ code: list[float]
31
+ full_delta: list[float]
32
+ horizon: int
33
+ action_dim: int
34
+
35
+
36
+ def build_spline_tangent_rows(
37
+ targets: Sequence[dict[str, Any]],
38
+ *,
39
+ obs_dim: int = 96,
40
+ text_dim: int = 64,
41
+ task_ids: Sequence[str] | None = None,
42
+ ) -> tuple[list[SplineTangentRow], list[str], int, int, int]:
43
+ """Build keyframe-spline training rows.
44
+
45
+ The learned variable is a compact local tangent chart: start, midpoint, and
46
+ endpoint residual keyframes. A deterministic smooth decoder maps this code
47
+ back to the full action horizon for support evaluation.
48
+ """
49
+
50
+ tasks = (
51
+ sorted({str(item.get("task_id", "unknown")) for item in targets})
52
+ if task_ids is None
53
+ else [str(task_id) for task_id in task_ids]
54
+ )
55
+ task_to_index = {task_id: index for index, task_id in enumerate(tasks)}
56
+ rows: list[SplineTangentRow] = []
57
+ max_horizon = 0
58
+ max_action_dim = 0
59
+ code_dim = 0
60
+ for item in targets:
61
+ delta_action = item.get("delta_action", [])
62
+ if not _is_numeric_matrix(delta_action):
63
+ continue
64
+ matrix = [[float(value) for value in row] for row in delta_action]
65
+ horizon = len(matrix)
66
+ action_dim = len(matrix[0])
67
+ if horizon <= 0 or action_dim <= 0:
68
+ continue
69
+ summary = item.get("tangent_summary", {})
70
+ start = _summary_or_matrix_row(summary, "start_delta", matrix, 0)
71
+ midpoint = _summary_or_matrix_row(summary, "midpoint_delta", matrix, horizon // 2)
72
+ endpoint = _summary_or_matrix_row(summary, "endpoint_delta", matrix, horizon - 1)
73
+ code = start + midpoint + endpoint
74
+ code_dim = max(code_dim, len(code))
75
+ max_horizon = max(max_horizon, horizon)
76
+ max_action_dim = max(max_action_dim, action_dim)
77
+ example = TangentExample(
78
+ group_id=str(item["group_id"]),
79
+ task_id=str(item.get("task_id", "unknown")),
80
+ candidate_type=str(item.get("candidate_type", "unknown")),
81
+ tangent_label=str(item.get("tangent_label", "unknown")),
82
+ delta_utility=float(item.get("delta_utility", 0.0)),
83
+ delta_action=matrix,
84
+ )
85
+ rows.append(
86
+ SplineTangentRow(
87
+ example=example,
88
+ condition=condition_vector(
89
+ item,
90
+ task_to_index=task_to_index,
91
+ obs_dim=obs_dim,
92
+ text_dim=text_dim,
93
+ ),
94
+ code=code,
95
+ full_delta=[value for row in matrix for value in row],
96
+ horizon=horizon,
97
+ action_dim=action_dim,
98
+ )
99
+ )
100
+ return rows, tasks, code_dim, max_horizon, max_action_dim
101
+
102
+
103
+ def decode_keyframe_spline(
104
+ code: Sequence[float],
105
+ *,
106
+ horizon: int,
107
+ action_dim: int,
108
+ ) -> list[float]:
109
+ if horizon <= 0:
110
+ raise ValueError("horizon must be positive")
111
+ if action_dim <= 0:
112
+ raise ValueError("action_dim must be positive")
113
+ values = _pad_or_truncate(code, 3 * action_dim)
114
+ start = values[:action_dim]
115
+ midpoint = values[action_dim : 2 * action_dim]
116
+ endpoint = values[2 * action_dim : 3 * action_dim]
117
+ rows: list[list[float]] = []
118
+ if horizon == 1:
119
+ rows = [endpoint]
120
+ else:
121
+ for index in range(horizon):
122
+ t = index / float(horizon - 1)
123
+ if t <= 0.5:
124
+ alpha = _smoothstep(t / 0.5)
125
+ row = [
126
+ (1.0 - alpha) * left + alpha * right
127
+ for left, right in zip(start, midpoint, strict=True)
128
+ ]
129
+ else:
130
+ alpha = _smoothstep((t - 0.5) / 0.5)
131
+ row = [
132
+ (1.0 - alpha) * left + alpha * right
133
+ for left, right in zip(midpoint, endpoint, strict=True)
134
+ ]
135
+ rows.append(row)
136
+ return [float(value) for row in rows for value in row]
137
+
138
+
139
+ def train_and_evaluate_spline_cvae(
140
+ targets: Sequence[dict[str, Any]],
141
+ *,
142
+ config: TangentCVAEConfig | None = None,
143
+ k_values: Sequence[int] = (1, 2, 4, 8, 16),
144
+ thresholds: Sequence[float] = (0.05, 0.1, 0.2, 0.4),
145
+ device: str = "auto",
146
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
147
+ if torch is None or DataLoader is None or TensorDataset is None:
148
+ raise RuntimeError("PyTorch is required to train the spline CVAE")
149
+ config = config or TangentCVAEConfig()
150
+ _validate_eval_args(k_values, thresholds)
151
+ rows, task_ids, code_dim, horizon, action_dim = build_spline_tangent_rows(
152
+ targets,
153
+ obs_dim=config.obs_dim,
154
+ text_dim=config.text_dim,
155
+ )
156
+ if not rows:
157
+ raise ValueError("no usable spline tangent rows")
158
+ split = _split_rows(rows, val_fraction=config.val_fraction, seed=config.seed)
159
+ train_positive = [
160
+ row for row in split["train"]
161
+ if row.example.tangent_label == "positive"
162
+ ]
163
+ if not train_positive:
164
+ raise ValueError("no train positive tangents")
165
+ condition_dim = len(rows[0].condition)
166
+ resolved_device = _resolve_device(device)
167
+ model = PositiveTangentCVAE(
168
+ condition_dim=condition_dim,
169
+ action_dim=code_dim,
170
+ hidden_dim=config.hidden_dim,
171
+ latent_dim=config.latent_dim,
172
+ ).to(resolved_device)
173
+ train_condition, train_code = _rows_to_tensors(
174
+ train_positive,
175
+ code_dim=code_dim,
176
+ device=resolved_device,
177
+ )
178
+ stats = _normalization_stats(train_condition, train_code)
179
+ train_condition = _normalize(train_condition, stats["condition_mean"], stats["condition_std"])
180
+ train_code = _normalize(train_code, stats["code_mean"], stats["code_std"])
181
+ generator = torch.Generator(device="cpu")
182
+ generator.manual_seed(int(config.seed))
183
+ loader = DataLoader(
184
+ TensorDataset(train_condition, train_code),
185
+ batch_size=config.batch_size,
186
+ shuffle=True,
187
+ generator=generator,
188
+ )
189
+ optimizer = torch.optim.AdamW(model.parameters(), lr=config.learning_rate)
190
+ history: list[dict[str, float]] = []
191
+ for epoch in range(1, config.epochs + 1):
192
+ model.train()
193
+ loss_sum = 0.0
194
+ recon_sum = 0.0
195
+ kl_sum = 0.0
196
+ count = 0
197
+ for condition_batch, code_batch in loader:
198
+ optimizer.zero_grad(set_to_none=True)
199
+ recon, mu, logvar = model(condition_batch, code_batch)
200
+ recon_loss = torch.mean((recon - code_batch) ** 2)
201
+ kl = -0.5 * torch.mean(1.0 + logvar - mu.pow(2) - logvar.exp())
202
+ loss = recon_loss + config.beta * kl
203
+ loss.backward()
204
+ optimizer.step()
205
+ batch_size = int(condition_batch.shape[0])
206
+ loss_sum += float(loss.detach()) * batch_size
207
+ recon_sum += float(recon_loss.detach()) * batch_size
208
+ kl_sum += float(kl.detach()) * batch_size
209
+ count += batch_size
210
+ if epoch == 1 or epoch == config.epochs or epoch % max(1, config.epochs // 10) == 0:
211
+ history.append(
212
+ {
213
+ "epoch": float(epoch),
214
+ "loss": loss_sum / max(count, 1),
215
+ "reconstruction_mse": recon_sum / max(count, 1),
216
+ "kl": kl_sum / max(count, 1),
217
+ }
218
+ )
219
+ report = evaluate_spline_cvae_support(
220
+ model,
221
+ rows,
222
+ split=split,
223
+ task_ids=task_ids,
224
+ code_dim=code_dim,
225
+ horizon=horizon,
226
+ action_dim=action_dim,
227
+ stats=stats,
228
+ config=config,
229
+ k_values=k_values,
230
+ thresholds=thresholds,
231
+ device=resolved_device,
232
+ )
233
+ report["train_history"] = history
234
+ artifact = {
235
+ "config": asdict(config),
236
+ "task_ids": task_ids,
237
+ "condition_dim": condition_dim,
238
+ "code_dim": code_dim,
239
+ "horizon": horizon,
240
+ "action_dim": action_dim,
241
+ "stats": {key: value.detach().cpu().tolist() for key, value in stats.items()},
242
+ "model_state_dict": model.state_dict(),
243
+ }
244
+ return report, artifact
245
+
246
+
247
+ def evaluate_spline_cvae_support(
248
+ model: Any,
249
+ rows: Sequence[SplineTangentRow],
250
+ *,
251
+ split: dict[str, list[SplineTangentRow]],
252
+ task_ids: Sequence[str],
253
+ code_dim: int,
254
+ horizon: int,
255
+ action_dim: int,
256
+ stats: dict[str, Any],
257
+ config: TangentCVAEConfig,
258
+ k_values: Sequence[int],
259
+ thresholds: Sequence[float],
260
+ device: Any,
261
+ ) -> dict[str, Any]:
262
+ max_k = max(int(k) for k in k_values)
263
+ val_by_group: dict[str, list[SplineTangentRow]] = defaultdict(list)
264
+ for row in split["val"]:
265
+ val_by_group[row.example.group_id].append(row)
266
+ model.eval()
267
+ groups: list[dict[str, Any]] = []
268
+ with torch.no_grad():
269
+ for group_id, group_rows in sorted(val_by_group.items()):
270
+ positives = [
271
+ row.example for row in group_rows
272
+ if row.example.tangent_label == "positive"
273
+ ]
274
+ if not positives:
275
+ continue
276
+ negatives = [
277
+ row.example for row in group_rows
278
+ if row.example.tangent_label == "negative"
279
+ ]
280
+ condition = torch.tensor(
281
+ [group_rows[0].condition],
282
+ dtype=torch.float32,
283
+ device=device,
284
+ )
285
+ condition = _normalize(
286
+ condition,
287
+ stats["condition_mean"],
288
+ stats["condition_std"],
289
+ )
290
+ proposals = _sample_decoded_proposals(
291
+ model,
292
+ condition,
293
+ count=max_k,
294
+ config=config,
295
+ stats=stats,
296
+ code_dim=code_dim,
297
+ horizon=horizon,
298
+ action_dim=action_dim,
299
+ group_id=group_id,
300
+ device=device,
301
+ )
302
+ groups.append(
303
+ _evaluate_generated_group(
304
+ group_id,
305
+ task_id=group_rows[0].example.task_id,
306
+ proposals=proposals,
307
+ positives=positives,
308
+ negatives=negatives,
309
+ k_values=k_values,
310
+ thresholds=thresholds,
311
+ )
312
+ )
313
+ return {
314
+ "report_type": "positive_tangent_spline_cvae_generator_eval",
315
+ "metric_scope": "offline_support_proxy",
316
+ "note": (
317
+ "Spline-CVAE proposals are sampled from train-only positive tangent "
318
+ "keyframes and decoded through a smooth keyframe spline before "
319
+ "heldout support evaluation."
320
+ ),
321
+ "config": asdict(config),
322
+ "task_ids": list(task_ids),
323
+ "code_dim": code_dim,
324
+ "horizon": horizon,
325
+ "action_dim": action_dim,
326
+ "num_examples": len(rows),
327
+ "num_groups": len({row.example.group_id for row in rows}),
328
+ "num_train_examples": len(split["train"]),
329
+ "num_val_examples": len(split["val"]),
330
+ "num_train_positive": sum(
331
+ 1 for row in split["train"] if row.example.tangent_label == "positive"
332
+ ),
333
+ "num_val_groups_with_positive": len(groups),
334
+ "label_counts": dict(Counter(row.example.tangent_label for row in rows)),
335
+ "train_positive_by_task": {
336
+ task_id: sum(
337
+ 1 for row in split["train"]
338
+ if row.example.task_id == task_id
339
+ and row.example.tangent_label == "positive"
340
+ )
341
+ for task_id in task_ids
342
+ },
343
+ "overall": _aggregate_rows(groups, k_values=k_values, thresholds=thresholds),
344
+ "per_task": {
345
+ task_id: _aggregate_rows(
346
+ [group for group in groups if group["task_id"] == task_id],
347
+ k_values=k_values,
348
+ thresholds=thresholds,
349
+ )
350
+ for task_id in task_ids
351
+ },
352
+ "groups": groups,
353
+ }
354
+
355
+
356
+ def _sample_decoded_proposals(
357
+ model: Any,
358
+ condition: Any,
359
+ *,
360
+ count: int,
361
+ config: TangentCVAEConfig,
362
+ stats: dict[str, Any],
363
+ code_dim: int,
364
+ horizon: int,
365
+ action_dim: int,
366
+ group_id: str,
367
+ device: Any,
368
+ ) -> list[list[float]]:
369
+ generator = torch.Generator(device=device.type if hasattr(device, "type") else "cpu")
370
+ seed = int(_stable_uniform(group_id, seed=config.seed) * (2**31 - 1))
371
+ generator.manual_seed(seed)
372
+ repeated_condition = condition.repeat(count, 1)
373
+ latent = torch.randn(
374
+ (count, config.latent_dim),
375
+ generator=generator,
376
+ device=device,
377
+ dtype=repeated_condition.dtype,
378
+ )
379
+ latent = latent * float(config.diversity_temperature)
380
+ decoded_code = model.decode(repeated_condition, latent)
381
+ decoded_code = _denormalize(decoded_code, stats["code_mean"], stats["code_std"])
382
+ codes = decoded_code[:, :code_dim].detach().cpu().tolist()
383
+ return [
384
+ decode_keyframe_spline(code, horizon=horizon, action_dim=action_dim)
385
+ for code in codes
386
+ ]
387
+
388
+
389
+ def _evaluate_generated_group(
390
+ group_id: str,
391
+ *,
392
+ task_id: str,
393
+ proposals: Sequence[Sequence[float]],
394
+ positives: Sequence[TangentExample],
395
+ negatives: Sequence[TangentExample],
396
+ k_values: Sequence[int],
397
+ thresholds: Sequence[float],
398
+ ) -> dict[str, Any]:
399
+ row: dict[str, Any] = {
400
+ "group_id": group_id,
401
+ "task_id": task_id,
402
+ "num_positive_targets": len(positives),
403
+ "num_negative_targets": len(negatives),
404
+ "num_proposals": len(proposals),
405
+ }
406
+ for k in k_values:
407
+ prefix = list(proposals[: int(k)])
408
+ pos_dist = _min_generated_distance(prefix, positives)
409
+ neg_dist = _min_generated_distance(prefix, negatives)
410
+ row[f"positive_min_rms_l2_at_{k}"] = pos_dist
411
+ row[f"negative_min_rms_l2_at_{k}"] = neg_dist
412
+ row[f"positive_closer_than_negative_at_{k}"] = (
413
+ None if pos_dist is None or neg_dist is None else pos_dist < neg_dist
414
+ )
415
+ for threshold in thresholds:
416
+ key = _threshold_key(threshold)
417
+ row[f"ptr_proxy_at_{k}_thr_{key}"] = (
418
+ None if pos_dist is None else pos_dist <= threshold
419
+ )
420
+ row[f"negative_near_at_{k}_thr_{key}"] = (
421
+ None if neg_dist is None else neg_dist <= threshold
422
+ )
423
+ return row
424
+
425
+
426
+ def _aggregate_rows(
427
+ rows: Sequence[dict[str, Any]],
428
+ *,
429
+ k_values: Sequence[int],
430
+ thresholds: Sequence[float],
431
+ ) -> dict[str, Any]:
432
+ output: dict[str, Any] = {"num_groups": len(rows)}
433
+ for k in k_values:
434
+ distances = [
435
+ float(row[f"positive_min_rms_l2_at_{k}"])
436
+ for row in rows
437
+ if row.get(f"positive_min_rms_l2_at_{k}") is not None
438
+ ]
439
+ output[f"mean_positive_min_rms_l2_at_{k}"] = _mean(distances)
440
+ output[f"median_positive_min_rms_l2_at_{k}"] = _median(distances)
441
+ closer = [
442
+ bool(row[f"positive_closer_than_negative_at_{k}"])
443
+ for row in rows
444
+ if row.get(f"positive_closer_than_negative_at_{k}") is not None
445
+ ]
446
+ output[f"positive_closer_than_negative_rate_at_{k}"] = _bool_rate(closer)
447
+ for threshold in thresholds:
448
+ key = _threshold_key(threshold)
449
+ output[f"ptr_proxy_at_{k}_thr_{key}"] = _bool_rate(
450
+ [
451
+ row[f"ptr_proxy_at_{k}_thr_{key}"]
452
+ for row in rows
453
+ if row.get(f"ptr_proxy_at_{k}_thr_{key}") is not None
454
+ ]
455
+ )
456
+ output[f"negative_near_at_{k}_thr_{key}"] = _bool_rate(
457
+ [
458
+ row[f"negative_near_at_{k}_thr_{key}"]
459
+ for row in rows
460
+ if row.get(f"negative_near_at_{k}_thr_{key}") is not None
461
+ ]
462
+ )
463
+ return output
464
+
465
+
466
+ def _rows_to_tensors(
467
+ rows: Sequence[SplineTangentRow],
468
+ *,
469
+ code_dim: int,
470
+ device: Any,
471
+ ) -> tuple[Any, Any]:
472
+ return (
473
+ torch.tensor([row.condition for row in rows], dtype=torch.float32, device=device),
474
+ torch.tensor(
475
+ [_pad_or_truncate(row.code, code_dim) for row in rows],
476
+ dtype=torch.float32,
477
+ device=device,
478
+ ),
479
+ )
480
+
481
+
482
+ def _normalization_stats(condition: Any, code: Any) -> dict[str, Any]:
483
+ return {
484
+ "condition_mean": condition.mean(dim=0, keepdim=True),
485
+ "condition_std": condition.std(dim=0, keepdim=True, unbiased=False).clamp(min=1.0e-4),
486
+ "code_mean": code.mean(dim=0, keepdim=True),
487
+ "code_std": code.std(dim=0, keepdim=True, unbiased=False).clamp(min=1.0e-4),
488
+ }
489
+
490
+
491
+ def _split_rows(
492
+ rows: Sequence[SplineTangentRow],
493
+ *,
494
+ val_fraction: float,
495
+ seed: int,
496
+ ) -> dict[str, list[SplineTangentRow]]:
497
+ train: list[SplineTangentRow] = []
498
+ val: list[SplineTangentRow] = []
499
+ for row in rows:
500
+ if _stable_uniform(row.example.group_id, seed=seed) < val_fraction:
501
+ val.append(row)
502
+ else:
503
+ train.append(row)
504
+ return {"train": train, "val": val}
505
+
506
+
507
+ def _summary_or_matrix_row(
508
+ summary: dict[str, Any],
509
+ key: str,
510
+ matrix: Sequence[Sequence[float]],
511
+ index: int,
512
+ ) -> list[float]:
513
+ values = summary.get(key)
514
+ if isinstance(values, list) and all(isinstance(value, (int, float)) for value in values):
515
+ return [float(value) for value in values]
516
+ row = matrix[max(0, min(index, len(matrix) - 1))]
517
+ return [float(value) for value in row]
518
+
519
+
520
+ def _min_generated_distance(
521
+ generated: Sequence[Sequence[float]],
522
+ targets: Sequence[TangentExample],
523
+ ) -> float | None:
524
+ if not generated or not targets:
525
+ return None
526
+ return min(
527
+ _rms_l2(generated_delta, target.flat_delta)
528
+ for generated_delta in generated
529
+ for target in targets
530
+ )
531
+
532
+
533
+ def _rms_l2(left: Sequence[float], right: Sequence[float]) -> float:
534
+ if len(left) != len(right):
535
+ size = min(len(left), len(right))
536
+ left = list(left[:size])
537
+ right = list(right[:size])
538
+ if not left:
539
+ return 0.0
540
+ return math.sqrt(
541
+ sum((float(a) - float(b)) ** 2 for a, b in zip(left, right, strict=True))
542
+ / len(left)
543
+ )
544
+
545
+
546
+ def _normalize(value: Any, mean: Any, std: Any) -> Any:
547
+ return (value - mean) / std
548
+
549
+
550
+ def _denormalize(value: Any, mean: Any, std: Any) -> Any:
551
+ return value * std + mean
552
+
553
+
554
+ def _pad_or_truncate(values: Sequence[float], size: int) -> list[float]:
555
+ output = [float(value) for value in values[:size]]
556
+ output.extend([0.0] * max(0, size - len(output)))
557
+ return output
558
+
559
+
560
+ def _smoothstep(value: float) -> float:
561
+ value = max(0.0, min(1.0, float(value)))
562
+ return value * value * (3.0 - 2.0 * value)
563
+
564
+
565
+ def _stable_uniform(value: str, *, seed: int) -> float:
566
+ digest = hashlib.sha256(f"{seed}:{value}".encode("utf-8")).digest()
567
+ integer = int.from_bytes(digest[:8], "big")
568
+ return integer / float(2**64 - 1)
569
+
570
+
571
+ def _threshold_key(value: float) -> str:
572
+ return f"{value:g}".replace(".", "p")
573
+
574
+
575
+ def _mean(values: Sequence[float]) -> float | None:
576
+ return sum(values) / len(values) if values else None
577
+
578
+
579
+ def _median(values: Sequence[float]) -> float | None:
580
+ if not values:
581
+ return None
582
+ ordered = sorted(values)
583
+ mid = len(ordered) // 2
584
+ if len(ordered) % 2:
585
+ return ordered[mid]
586
+ return 0.5 * (ordered[mid - 1] + ordered[mid])
587
+
588
+
589
+ def _bool_rate(values: Sequence[bool]) -> float | None:
590
+ return sum(bool(value) for value in values) / len(values) if values else None
591
+
592
+
593
+ def _validate_eval_args(k_values: Sequence[int], thresholds: Sequence[float]) -> None:
594
+ if any(k <= 0 for k in k_values):
595
+ raise ValueError("k_values must be positive")
596
+ if any(threshold < 0 for threshold in thresholds):
597
+ raise ValueError("thresholds must be non-negative")
598
+
599
+
600
+ def _resolve_device(device: str) -> Any:
601
+ if device == "auto":
602
+ return torch.device("cuda" if torch.cuda.is_available() else "cpu")
603
+ resolved = torch.device(device)
604
+ if resolved.type == "cuda" and not torch.cuda.is_available():
605
+ raise RuntimeError("CUDA requested but not available")
606
+ return resolved
607
+
608
+
609
+ def _is_numeric_matrix(value: Any) -> bool:
610
+ return (
611
+ isinstance(value, list)
612
+ and bool(value)
613
+ and all(
614
+ isinstance(row, list)
615
+ and all(isinstance(item, (int, float)) for item in row)
616
+ for row in value
617
+ )
618
+ )
workspace/dovla_cil/generation/tangent_spline_flow.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Sequence
4
+ from dataclasses import asdict, dataclass
5
+ from typing import Any
6
+
7
+ from dovla_cil.generation.tangent_spline_cvae import (
8
+ _aggregate_rows,
9
+ _denormalize,
10
+ _evaluate_generated_group,
11
+ _normalize,
12
+ _normalization_stats,
13
+ _resolve_device,
14
+ _rows_to_tensors,
15
+ _split_rows,
16
+ _stable_uniform,
17
+ _validate_eval_args,
18
+ build_spline_tangent_rows,
19
+ decode_keyframe_spline,
20
+ )
21
+
22
+ try:
23
+ import torch
24
+ from torch import nn
25
+ from torch.utils.data import DataLoader, TensorDataset
26
+ except ImportError: # pragma: no cover - login shells may not have torch
27
+ torch = None
28
+ nn = None
29
+ DataLoader = None
30
+ TensorDataset = None
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class SplineFlowConfig:
35
+ obs_dim: int = 96
36
+ text_dim: int = 64
37
+ hidden_dim: int = 256
38
+ batch_size: int = 128
39
+ epochs: int = 300
40
+ learning_rate: float = 1.0e-3
41
+ val_fraction: float = 0.2
42
+ seed: int = 0
43
+ sample_steps: int = 16
44
+ noise_scale: float = 1.0
45
+
46
+ def __post_init__(self) -> None:
47
+ if self.obs_dim <= 0:
48
+ raise ValueError("obs_dim must be positive")
49
+ if self.text_dim <= 0:
50
+ raise ValueError("text_dim must be positive")
51
+ if self.hidden_dim <= 0:
52
+ raise ValueError("hidden_dim must be positive")
53
+ if self.batch_size <= 0:
54
+ raise ValueError("batch_size must be positive")
55
+ if self.epochs <= 0:
56
+ raise ValueError("epochs must be positive")
57
+ if self.learning_rate <= 0:
58
+ raise ValueError("learning_rate must be positive")
59
+ if not 0.0 < self.val_fraction < 1.0:
60
+ raise ValueError("val_fraction must be in (0, 1)")
61
+ if self.sample_steps <= 0:
62
+ raise ValueError("sample_steps must be positive")
63
+ if self.noise_scale <= 0:
64
+ raise ValueError("noise_scale must be positive")
65
+
66
+
67
+ if nn is not None:
68
+
69
+ class ConditionalSplineFlow(nn.Module):
70
+ def __init__(
71
+ self,
72
+ *,
73
+ condition_dim: int,
74
+ code_dim: int,
75
+ hidden_dim: int,
76
+ ) -> None:
77
+ super().__init__()
78
+ self.condition_dim = int(condition_dim)
79
+ self.code_dim = int(code_dim)
80
+ self.net = nn.Sequential(
81
+ nn.Linear(self.condition_dim + self.code_dim + 1, hidden_dim),
82
+ nn.LayerNorm(hidden_dim),
83
+ nn.GELU(),
84
+ nn.Linear(hidden_dim, hidden_dim),
85
+ nn.GELU(),
86
+ nn.Linear(hidden_dim, self.code_dim),
87
+ )
88
+
89
+ def forward(self, condition, x_t, t):
90
+ if t.ndim == 1:
91
+ t = t[:, None]
92
+ return self.net(torch.cat([condition, x_t, t], dim=-1))
93
+
94
+ else: # pragma: no cover - exercised only when torch is absent
95
+ ConditionalSplineFlow = None
96
+
97
+
98
+ def train_and_evaluate_spline_flow(
99
+ targets: Sequence[dict[str, Any]],
100
+ *,
101
+ config: SplineFlowConfig | None = None,
102
+ k_values: Sequence[int] = (1, 2, 4, 8, 16),
103
+ thresholds: Sequence[float] = (0.05, 0.1, 0.2, 0.4),
104
+ device: str = "auto",
105
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
106
+ if torch is None or nn is None or DataLoader is None or TensorDataset is None:
107
+ raise RuntimeError("PyTorch is required to train the spline flow")
108
+ config = config or SplineFlowConfig()
109
+ _validate_eval_args(k_values, thresholds)
110
+ rows, task_ids, code_dim, horizon, action_dim = build_spline_tangent_rows(
111
+ targets,
112
+ obs_dim=config.obs_dim,
113
+ text_dim=config.text_dim,
114
+ )
115
+ if not rows:
116
+ raise ValueError("no usable spline tangent rows")
117
+ split = _split_rows(rows, val_fraction=config.val_fraction, seed=config.seed)
118
+ train_positive = [
119
+ row for row in split["train"]
120
+ if row.example.tangent_label == "positive"
121
+ ]
122
+ if not train_positive:
123
+ raise ValueError("no train positive tangents")
124
+ condition_dim = len(rows[0].condition)
125
+ resolved_device = _resolve_device(device)
126
+ model = ConditionalSplineFlow(
127
+ condition_dim=condition_dim,
128
+ code_dim=code_dim,
129
+ hidden_dim=config.hidden_dim,
130
+ ).to(resolved_device)
131
+ train_condition, train_code = _rows_to_tensors(
132
+ train_positive,
133
+ code_dim=code_dim,
134
+ device=resolved_device,
135
+ )
136
+ stats = _normalization_stats(train_condition, train_code)
137
+ train_condition = _normalize(train_condition, stats["condition_mean"], stats["condition_std"])
138
+ train_code = _normalize(train_code, stats["code_mean"], stats["code_std"])
139
+ generator = torch.Generator(device="cpu")
140
+ generator.manual_seed(int(config.seed))
141
+ loader = DataLoader(
142
+ TensorDataset(train_condition, train_code),
143
+ batch_size=config.batch_size,
144
+ shuffle=True,
145
+ generator=generator,
146
+ )
147
+ optimizer = torch.optim.AdamW(model.parameters(), lr=config.learning_rate)
148
+ history: list[dict[str, float]] = []
149
+ for epoch in range(1, config.epochs + 1):
150
+ model.train()
151
+ loss_sum = 0.0
152
+ count = 0
153
+ for condition_batch, code_batch in loader:
154
+ noise = torch.randn_like(code_batch) * float(config.noise_scale)
155
+ t = torch.rand(
156
+ (code_batch.shape[0], 1),
157
+ device=code_batch.device,
158
+ dtype=code_batch.dtype,
159
+ )
160
+ x_t = (1.0 - t) * noise + t * code_batch
161
+ target_velocity = code_batch - noise
162
+ predicted_velocity = model(condition_batch, x_t, t)
163
+ loss = torch.mean((predicted_velocity - target_velocity) ** 2)
164
+ optimizer.zero_grad(set_to_none=True)
165
+ loss.backward()
166
+ optimizer.step()
167
+ batch_size = int(code_batch.shape[0])
168
+ loss_sum += float(loss.detach()) * batch_size
169
+ count += batch_size
170
+ if epoch == 1 or epoch == config.epochs or epoch % max(1, config.epochs // 10) == 0:
171
+ history.append({"epoch": float(epoch), "flow_mse": loss_sum / max(count, 1)})
172
+ report = evaluate_spline_flow_support(
173
+ model,
174
+ rows,
175
+ split=split,
176
+ task_ids=task_ids,
177
+ code_dim=code_dim,
178
+ horizon=horizon,
179
+ action_dim=action_dim,
180
+ stats=stats,
181
+ config=config,
182
+ k_values=k_values,
183
+ thresholds=thresholds,
184
+ device=resolved_device,
185
+ )
186
+ report["train_history"] = history
187
+ artifact = {
188
+ "config": asdict(config),
189
+ "task_ids": task_ids,
190
+ "condition_dim": condition_dim,
191
+ "code_dim": code_dim,
192
+ "horizon": horizon,
193
+ "action_dim": action_dim,
194
+ "stats": {key: value.detach().cpu().tolist() for key, value in stats.items()},
195
+ "model_state_dict": model.state_dict(),
196
+ }
197
+ return report, artifact
198
+
199
+
200
+ def evaluate_spline_flow_support(
201
+ model: Any,
202
+ rows: Sequence[Any],
203
+ *,
204
+ split: dict[str, list[Any]],
205
+ task_ids: Sequence[str],
206
+ code_dim: int,
207
+ horizon: int,
208
+ action_dim: int,
209
+ stats: dict[str, Any],
210
+ config: SplineFlowConfig,
211
+ k_values: Sequence[int],
212
+ thresholds: Sequence[float],
213
+ device: Any,
214
+ ) -> dict[str, Any]:
215
+ max_k = max(int(k) for k in k_values)
216
+ val_by_group: dict[str, list[Any]] = {}
217
+ for row in split["val"]:
218
+ val_by_group.setdefault(row.example.group_id, []).append(row)
219
+ groups: list[dict[str, Any]] = []
220
+ model.eval()
221
+ with torch.no_grad():
222
+ for group_id, group_rows in sorted(val_by_group.items()):
223
+ positives = [
224
+ row.example for row in group_rows
225
+ if row.example.tangent_label == "positive"
226
+ ]
227
+ if not positives:
228
+ continue
229
+ negatives = [
230
+ row.example for row in group_rows
231
+ if row.example.tangent_label == "negative"
232
+ ]
233
+ condition = torch.tensor(
234
+ [group_rows[0].condition],
235
+ dtype=torch.float32,
236
+ device=device,
237
+ )
238
+ condition = _normalize(
239
+ condition,
240
+ stats["condition_mean"],
241
+ stats["condition_std"],
242
+ )
243
+ proposals = _sample_decoded_proposals(
244
+ model,
245
+ condition,
246
+ count=max_k,
247
+ config=config,
248
+ stats=stats,
249
+ code_dim=code_dim,
250
+ horizon=horizon,
251
+ action_dim=action_dim,
252
+ group_id=group_id,
253
+ device=device,
254
+ )
255
+ groups.append(
256
+ _evaluate_generated_group(
257
+ group_id,
258
+ task_id=group_rows[0].example.task_id,
259
+ proposals=proposals,
260
+ positives=positives,
261
+ negatives=negatives,
262
+ k_values=k_values,
263
+ thresholds=thresholds,
264
+ )
265
+ )
266
+ return {
267
+ "report_type": "positive_tangent_spline_flow_generator_eval",
268
+ "metric_scope": "offline_support_proxy",
269
+ "note": (
270
+ "Spline-flow proposals are sampled by integrating a conditional "
271
+ "flow-matching vector field in positive keyframe tangent space, "
272
+ "then decoded to full action chunks."
273
+ ),
274
+ "config": asdict(config),
275
+ "task_ids": list(task_ids),
276
+ "code_dim": code_dim,
277
+ "horizon": horizon,
278
+ "action_dim": action_dim,
279
+ "num_examples": len(rows),
280
+ "num_groups": len({row.example.group_id for row in rows}),
281
+ "num_train_examples": len(split["train"]),
282
+ "num_val_examples": len(split["val"]),
283
+ "num_train_positive": sum(
284
+ 1 for row in split["train"] if row.example.tangent_label == "positive"
285
+ ),
286
+ "num_val_groups_with_positive": len(groups),
287
+ "overall": _aggregate_rows(groups, k_values=k_values, thresholds=thresholds),
288
+ "per_task": {
289
+ task_id: _aggregate_rows(
290
+ [group for group in groups if group["task_id"] == task_id],
291
+ k_values=k_values,
292
+ thresholds=thresholds,
293
+ )
294
+ for task_id in task_ids
295
+ },
296
+ "groups": groups,
297
+ }
298
+
299
+
300
+ def _sample_decoded_proposals(
301
+ model: Any,
302
+ condition: Any,
303
+ *,
304
+ count: int,
305
+ config: SplineFlowConfig,
306
+ stats: dict[str, Any],
307
+ code_dim: int,
308
+ horizon: int,
309
+ action_dim: int,
310
+ group_id: str,
311
+ device: Any,
312
+ ) -> list[list[float]]:
313
+ generator = torch.Generator(device=device.type if hasattr(device, "type") else "cpu")
314
+ seed = int(_stable_uniform(group_id, seed=config.seed) * (2**31 - 1))
315
+ generator.manual_seed(seed)
316
+ repeated_condition = condition.repeat(count, 1)
317
+ x = torch.randn(
318
+ (count, code_dim),
319
+ generator=generator,
320
+ device=device,
321
+ dtype=repeated_condition.dtype,
322
+ ) * float(config.noise_scale)
323
+ dt = 1.0 / float(config.sample_steps)
324
+ for step in range(config.sample_steps):
325
+ t_value = (step + 0.5) * dt
326
+ t = torch.full(
327
+ (count, 1),
328
+ t_value,
329
+ device=device,
330
+ dtype=repeated_condition.dtype,
331
+ )
332
+ x = x + dt * model(repeated_condition, x, t)
333
+ decoded_code = _denormalize(x, stats["code_mean"], stats["code_std"])
334
+ codes = decoded_code[:, :code_dim].detach().cpu().tolist()
335
+ return [
336
+ decode_keyframe_spline(code, horizon=horizon, action_dim=action_dim)
337
+ for code in codes
338
+ ]
workspace/dovla_cil/generation/tangent_spline_guided_flow.py ADDED
@@ -0,0 +1,533 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections import Counter
4
+ from collections.abc import Sequence
5
+ from dataclasses import asdict, dataclass
6
+ from typing import Any
7
+
8
+ from dovla_cil.generation.tangent_spline_cvae import (
9
+ SplineTangentRow,
10
+ _aggregate_rows,
11
+ _denormalize,
12
+ _evaluate_generated_group,
13
+ _normalize,
14
+ _normalization_stats,
15
+ _pad_or_truncate,
16
+ _resolve_device,
17
+ _rows_to_tensors,
18
+ _split_rows,
19
+ _stable_uniform,
20
+ _validate_eval_args,
21
+ build_spline_tangent_rows,
22
+ decode_keyframe_spline,
23
+ )
24
+ from dovla_cil.generation.tangent_spline_flow import ConditionalSplineFlow
25
+
26
+ try:
27
+ import torch
28
+ from torch import nn
29
+ from torch.utils.data import DataLoader, TensorDataset
30
+ except ImportError: # pragma: no cover - login shells may not have torch
31
+ torch = None
32
+ nn = None
33
+ DataLoader = None
34
+ TensorDataset = None
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class GuidedSplineFlowConfig:
39
+ obs_dim: int = 96
40
+ text_dim: int = 64
41
+ hidden_dim: int = 256
42
+ utility_hidden_dim: int = 256
43
+ batch_size: int = 128
44
+ utility_batch_size: int = 256
45
+ epochs: int = 300
46
+ utility_epochs: int = 120
47
+ learning_rate: float = 1.0e-3
48
+ utility_learning_rate: float = 1.0e-3
49
+ val_fraction: float = 0.2
50
+ seed: int = 0
51
+ sample_steps: int = 16
52
+ noise_scale: float = 1.0
53
+ guidance_scale: float = 1.0
54
+ guidance_grad_clip: float = 1.0
55
+ proposal_pool_multiplier: int = 2
56
+ utility_positive_weight: float = 0.0
57
+
58
+ def __post_init__(self) -> None:
59
+ if self.obs_dim <= 0:
60
+ raise ValueError("obs_dim must be positive")
61
+ if self.text_dim <= 0:
62
+ raise ValueError("text_dim must be positive")
63
+ if self.hidden_dim <= 0:
64
+ raise ValueError("hidden_dim must be positive")
65
+ if self.utility_hidden_dim <= 0:
66
+ raise ValueError("utility_hidden_dim must be positive")
67
+ if self.batch_size <= 0:
68
+ raise ValueError("batch_size must be positive")
69
+ if self.utility_batch_size <= 0:
70
+ raise ValueError("utility_batch_size must be positive")
71
+ if self.epochs <= 0:
72
+ raise ValueError("epochs must be positive")
73
+ if self.utility_epochs <= 0:
74
+ raise ValueError("utility_epochs must be positive")
75
+ if self.learning_rate <= 0:
76
+ raise ValueError("learning_rate must be positive")
77
+ if self.utility_learning_rate <= 0:
78
+ raise ValueError("utility_learning_rate must be positive")
79
+ if not 0.0 < self.val_fraction < 1.0:
80
+ raise ValueError("val_fraction must be in (0, 1)")
81
+ if self.sample_steps <= 0:
82
+ raise ValueError("sample_steps must be positive")
83
+ if self.noise_scale <= 0:
84
+ raise ValueError("noise_scale must be positive")
85
+ if self.guidance_scale < 0:
86
+ raise ValueError("guidance_scale must be non-negative")
87
+ if self.guidance_grad_clip <= 0:
88
+ raise ValueError("guidance_grad_clip must be positive")
89
+ if self.proposal_pool_multiplier <= 0:
90
+ raise ValueError("proposal_pool_multiplier must be positive")
91
+ if self.utility_positive_weight < 0:
92
+ raise ValueError("utility_positive_weight must be non-negative")
93
+
94
+
95
+ if nn is not None:
96
+
97
+ class SplineUtilityHead(nn.Module):
98
+ def __init__(
99
+ self,
100
+ *,
101
+ condition_dim: int,
102
+ code_dim: int,
103
+ hidden_dim: int,
104
+ ) -> None:
105
+ super().__init__()
106
+ self.condition_dim = int(condition_dim)
107
+ self.code_dim = int(code_dim)
108
+ self.net = nn.Sequential(
109
+ nn.Linear(self.condition_dim + self.code_dim, hidden_dim),
110
+ nn.LayerNorm(hidden_dim),
111
+ nn.GELU(),
112
+ nn.Linear(hidden_dim, hidden_dim),
113
+ nn.GELU(),
114
+ nn.Linear(hidden_dim, 1),
115
+ )
116
+
117
+ def forward(self, condition, code):
118
+ return self.net(torch.cat([condition, code], dim=-1)).squeeze(-1)
119
+
120
+ else: # pragma: no cover - exercised only when torch is absent
121
+ SplineUtilityHead = None
122
+
123
+
124
+ def train_and_evaluate_guided_spline_flow(
125
+ targets: Sequence[dict[str, Any]],
126
+ *,
127
+ config: GuidedSplineFlowConfig | None = None,
128
+ k_values: Sequence[int] = (1, 2, 4, 8, 16),
129
+ thresholds: Sequence[float] = (0.05, 0.1, 0.2, 0.4),
130
+ device: str = "auto",
131
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
132
+ if (
133
+ torch is None
134
+ or nn is None
135
+ or DataLoader is None
136
+ or TensorDataset is None
137
+ or ConditionalSplineFlow is None
138
+ or SplineUtilityHead is None
139
+ ):
140
+ raise RuntimeError("PyTorch is required to train the guided spline flow")
141
+ config = config or GuidedSplineFlowConfig()
142
+ _validate_eval_args(k_values, thresholds)
143
+ rows, task_ids, code_dim, horizon, action_dim = build_spline_tangent_rows(
144
+ targets,
145
+ obs_dim=config.obs_dim,
146
+ text_dim=config.text_dim,
147
+ )
148
+ if not rows:
149
+ raise ValueError("no usable spline tangent rows")
150
+ split = _split_rows(rows, val_fraction=config.val_fraction, seed=config.seed)
151
+ train_positive = [
152
+ row for row in split["train"]
153
+ if row.example.tangent_label == "positive"
154
+ ]
155
+ train_negative = [
156
+ row for row in split["train"]
157
+ if row.example.tangent_label == "negative"
158
+ ]
159
+ if not train_positive:
160
+ raise ValueError("no train positive tangents")
161
+ if not train_negative:
162
+ raise ValueError("no train negative tangents for utility guidance")
163
+
164
+ condition_dim = len(rows[0].condition)
165
+ resolved_device = _resolve_device(device)
166
+ flow_model = ConditionalSplineFlow(
167
+ condition_dim=condition_dim,
168
+ code_dim=code_dim,
169
+ hidden_dim=config.hidden_dim,
170
+ ).to(resolved_device)
171
+ utility_head = SplineUtilityHead(
172
+ condition_dim=condition_dim,
173
+ code_dim=code_dim,
174
+ hidden_dim=config.utility_hidden_dim,
175
+ ).to(resolved_device)
176
+
177
+ train_condition, train_code = _rows_to_tensors(
178
+ train_positive,
179
+ code_dim=code_dim,
180
+ device=resolved_device,
181
+ )
182
+ stats = _normalization_stats(train_condition, train_code)
183
+ train_condition = _normalize(train_condition, stats["condition_mean"], stats["condition_std"])
184
+ train_code = _normalize(train_code, stats["code_mean"], stats["code_std"])
185
+ flow_history = _train_flow_model(
186
+ flow_model,
187
+ train_condition,
188
+ train_code,
189
+ config=config,
190
+ )
191
+ utility_history = _train_utility_head(
192
+ utility_head,
193
+ train_positive=train_positive,
194
+ train_negative=train_negative,
195
+ code_dim=code_dim,
196
+ stats=stats,
197
+ config=config,
198
+ device=resolved_device,
199
+ )
200
+ report = evaluate_guided_spline_flow_support(
201
+ flow_model,
202
+ utility_head,
203
+ rows,
204
+ split=split,
205
+ task_ids=task_ids,
206
+ code_dim=code_dim,
207
+ horizon=horizon,
208
+ action_dim=action_dim,
209
+ stats=stats,
210
+ config=config,
211
+ k_values=k_values,
212
+ thresholds=thresholds,
213
+ device=resolved_device,
214
+ )
215
+ report["train_history"] = flow_history
216
+ report["utility_train_history"] = utility_history
217
+ artifact = {
218
+ "config": asdict(config),
219
+ "task_ids": task_ids,
220
+ "condition_dim": condition_dim,
221
+ "code_dim": code_dim,
222
+ "horizon": horizon,
223
+ "action_dim": action_dim,
224
+ "stats": {key: value.detach().cpu().tolist() for key, value in stats.items()},
225
+ "flow_model_state_dict": flow_model.state_dict(),
226
+ "utility_head_state_dict": utility_head.state_dict(),
227
+ }
228
+ return report, artifact
229
+
230
+
231
+ def evaluate_guided_spline_flow_support(
232
+ flow_model: Any,
233
+ utility_head: Any,
234
+ rows: Sequence[SplineTangentRow],
235
+ *,
236
+ split: dict[str, list[SplineTangentRow]],
237
+ task_ids: Sequence[str],
238
+ code_dim: int,
239
+ horizon: int,
240
+ action_dim: int,
241
+ stats: dict[str, Any],
242
+ config: GuidedSplineFlowConfig,
243
+ k_values: Sequence[int],
244
+ thresholds: Sequence[float],
245
+ device: Any,
246
+ ) -> dict[str, Any]:
247
+ max_k = max(int(k) for k in k_values)
248
+ val_by_group: dict[str, list[SplineTangentRow]] = {}
249
+ for row in split["val"]:
250
+ val_by_group.setdefault(row.example.group_id, []).append(row)
251
+ groups: list[dict[str, Any]] = []
252
+ flow_model.eval()
253
+ utility_head.eval()
254
+ for group_id, group_rows in sorted(val_by_group.items()):
255
+ positives = [
256
+ row.example for row in group_rows
257
+ if row.example.tangent_label == "positive"
258
+ ]
259
+ if not positives:
260
+ continue
261
+ negatives = [
262
+ row.example for row in group_rows
263
+ if row.example.tangent_label == "negative"
264
+ ]
265
+ condition = torch.tensor(
266
+ [group_rows[0].condition],
267
+ dtype=torch.float32,
268
+ device=device,
269
+ )
270
+ condition = _normalize(
271
+ condition,
272
+ stats["condition_mean"],
273
+ stats["condition_std"],
274
+ )
275
+ proposals = _sample_guided_decoded_proposals(
276
+ flow_model,
277
+ utility_head,
278
+ condition,
279
+ count=max_k,
280
+ config=config,
281
+ stats=stats,
282
+ code_dim=code_dim,
283
+ horizon=horizon,
284
+ action_dim=action_dim,
285
+ group_id=group_id,
286
+ device=device,
287
+ )
288
+ groups.append(
289
+ _evaluate_generated_group(
290
+ group_id,
291
+ task_id=group_rows[0].example.task_id,
292
+ proposals=proposals,
293
+ positives=positives,
294
+ negatives=negatives,
295
+ k_values=k_values,
296
+ thresholds=thresholds,
297
+ )
298
+ )
299
+ return {
300
+ "report_type": "positive_tangent_guided_spline_flow_generator_eval",
301
+ "metric_scope": "offline_support_proxy",
302
+ "note": (
303
+ "Guided spline-flow proposals combine positive-keyframe flow matching "
304
+ "with a train-only positive-vs-negative utility head. Sampling follows "
305
+ "the flow field while ascending the learned local causal utility "
306
+ "gradient in normalized spline tangent space."
307
+ ),
308
+ "config": asdict(config),
309
+ "task_ids": list(task_ids),
310
+ "code_dim": code_dim,
311
+ "horizon": horizon,
312
+ "action_dim": action_dim,
313
+ "num_examples": len(rows),
314
+ "num_groups": len({row.example.group_id for row in rows}),
315
+ "num_train_examples": len(split["train"]),
316
+ "num_val_examples": len(split["val"]),
317
+ "num_train_positive": sum(
318
+ 1 for row in split["train"] if row.example.tangent_label == "positive"
319
+ ),
320
+ "num_train_negative": sum(
321
+ 1 for row in split["train"] if row.example.tangent_label == "negative"
322
+ ),
323
+ "num_val_groups_with_positive": len(groups),
324
+ "label_counts": dict(Counter(row.example.tangent_label for row in rows)),
325
+ "train_positive_by_task": {
326
+ task_id: sum(
327
+ 1 for row in split["train"]
328
+ if row.example.task_id == task_id
329
+ and row.example.tangent_label == "positive"
330
+ )
331
+ for task_id in task_ids
332
+ },
333
+ "train_negative_by_task": {
334
+ task_id: sum(
335
+ 1 for row in split["train"]
336
+ if row.example.task_id == task_id
337
+ and row.example.tangent_label == "negative"
338
+ )
339
+ for task_id in task_ids
340
+ },
341
+ "overall": _aggregate_rows(groups, k_values=k_values, thresholds=thresholds),
342
+ "per_task": {
343
+ task_id: _aggregate_rows(
344
+ [group for group in groups if group["task_id"] == task_id],
345
+ k_values=k_values,
346
+ thresholds=thresholds,
347
+ )
348
+ for task_id in task_ids
349
+ },
350
+ "groups": groups,
351
+ }
352
+
353
+
354
+ def _train_flow_model(
355
+ model: Any,
356
+ train_condition: Any,
357
+ train_code: Any,
358
+ *,
359
+ config: GuidedSplineFlowConfig,
360
+ ) -> list[dict[str, float]]:
361
+ generator = torch.Generator(device="cpu")
362
+ generator.manual_seed(int(config.seed))
363
+ loader = DataLoader(
364
+ TensorDataset(train_condition, train_code),
365
+ batch_size=config.batch_size,
366
+ shuffle=True,
367
+ generator=generator,
368
+ )
369
+ optimizer = torch.optim.AdamW(model.parameters(), lr=config.learning_rate)
370
+ history: list[dict[str, float]] = []
371
+ for epoch in range(1, config.epochs + 1):
372
+ model.train()
373
+ loss_sum = 0.0
374
+ count = 0
375
+ for condition_batch, code_batch in loader:
376
+ noise = torch.randn_like(code_batch) * float(config.noise_scale)
377
+ t = torch.rand(
378
+ (code_batch.shape[0], 1),
379
+ device=code_batch.device,
380
+ dtype=code_batch.dtype,
381
+ )
382
+ x_t = (1.0 - t) * noise + t * code_batch
383
+ target_velocity = code_batch - noise
384
+ predicted_velocity = model(condition_batch, x_t, t)
385
+ loss = torch.mean((predicted_velocity - target_velocity) ** 2)
386
+ optimizer.zero_grad(set_to_none=True)
387
+ loss.backward()
388
+ optimizer.step()
389
+ batch_size = int(code_batch.shape[0])
390
+ loss_sum += float(loss.detach()) * batch_size
391
+ count += batch_size
392
+ if epoch == 1 or epoch == config.epochs or epoch % max(1, config.epochs // 10) == 0:
393
+ history.append({"epoch": float(epoch), "flow_mse": loss_sum / max(count, 1)})
394
+ return history
395
+
396
+
397
+ def _train_utility_head(
398
+ utility_head: Any,
399
+ *,
400
+ train_positive: Sequence[SplineTangentRow],
401
+ train_negative: Sequence[SplineTangentRow],
402
+ code_dim: int,
403
+ stats: dict[str, Any],
404
+ config: GuidedSplineFlowConfig,
405
+ device: Any,
406
+ ) -> list[dict[str, float]]:
407
+ utility_rows = list(train_positive) + list(train_negative)
408
+ condition = torch.tensor(
409
+ [row.condition for row in utility_rows],
410
+ dtype=torch.float32,
411
+ device=device,
412
+ )
413
+ code = torch.tensor(
414
+ [_pad_or_truncate(row.code, code_dim) for row in utility_rows],
415
+ dtype=torch.float32,
416
+ device=device,
417
+ )
418
+ labels = torch.tensor(
419
+ [1.0 if row.example.tangent_label == "positive" else 0.0 for row in utility_rows],
420
+ dtype=torch.float32,
421
+ device=device,
422
+ )
423
+ condition = _normalize(condition, stats["condition_mean"], stats["condition_std"])
424
+ code = _normalize(code, stats["code_mean"], stats["code_std"])
425
+ generator = torch.Generator(device="cpu")
426
+ generator.manual_seed(int(config.seed) + 17)
427
+ loader = DataLoader(
428
+ TensorDataset(condition, code, labels),
429
+ batch_size=config.utility_batch_size,
430
+ shuffle=True,
431
+ generator=generator,
432
+ )
433
+ if config.utility_positive_weight > 0:
434
+ positive_weight = float(config.utility_positive_weight)
435
+ else:
436
+ positive_weight = min(32.0, len(train_negative) / max(len(train_positive), 1))
437
+ pos_weight = torch.tensor([positive_weight], dtype=torch.float32, device=device)
438
+ loss_fn = nn.BCEWithLogitsLoss(pos_weight=pos_weight)
439
+ optimizer = torch.optim.AdamW(utility_head.parameters(), lr=config.utility_learning_rate)
440
+ history: list[dict[str, float]] = []
441
+ for epoch in range(1, config.utility_epochs + 1):
442
+ utility_head.train()
443
+ loss_sum = 0.0
444
+ correct = 0
445
+ count = 0
446
+ for condition_batch, code_batch, label_batch in loader:
447
+ logits = utility_head(condition_batch, code_batch)
448
+ loss = loss_fn(logits, label_batch)
449
+ optimizer.zero_grad(set_to_none=True)
450
+ loss.backward()
451
+ optimizer.step()
452
+ batch_size = int(label_batch.shape[0])
453
+ loss_sum += float(loss.detach()) * batch_size
454
+ predictions = torch.sigmoid(logits.detach()) >= 0.5
455
+ correct += int((predictions == (label_batch >= 0.5)).sum().item())
456
+ count += batch_size
457
+ if (
458
+ epoch == 1
459
+ or epoch == config.utility_epochs
460
+ or epoch % max(1, config.utility_epochs // 10) == 0
461
+ ):
462
+ history.append(
463
+ {
464
+ "epoch": float(epoch),
465
+ "utility_bce": loss_sum / max(count, 1),
466
+ "utility_accuracy": correct / max(count, 1),
467
+ "positive_weight": positive_weight,
468
+ }
469
+ )
470
+ return history
471
+
472
+
473
+ def _sample_guided_decoded_proposals(
474
+ flow_model: Any,
475
+ utility_head: Any,
476
+ condition: Any,
477
+ *,
478
+ count: int,
479
+ config: GuidedSplineFlowConfig,
480
+ stats: dict[str, Any],
481
+ code_dim: int,
482
+ horizon: int,
483
+ action_dim: int,
484
+ group_id: str,
485
+ device: Any,
486
+ ) -> list[list[float]]:
487
+ pool_count = int(count) * int(config.proposal_pool_multiplier)
488
+ generator = torch.Generator(device=device.type if hasattr(device, "type") else "cpu")
489
+ seed = int(_stable_uniform(group_id, seed=config.seed) * (2**31 - 1))
490
+ generator.manual_seed(seed)
491
+ repeated_condition = condition.repeat(pool_count, 1)
492
+ x = torch.randn(
493
+ (pool_count, code_dim),
494
+ generator=generator,
495
+ device=device,
496
+ dtype=repeated_condition.dtype,
497
+ ) * float(config.noise_scale)
498
+ dt = 1.0 / float(config.sample_steps)
499
+ for step in range(config.sample_steps):
500
+ t_value = (step + 0.5) * dt
501
+ t = torch.full(
502
+ (pool_count, 1),
503
+ t_value,
504
+ device=device,
505
+ dtype=repeated_condition.dtype,
506
+ )
507
+ with torch.no_grad():
508
+ velocity = flow_model(repeated_condition, x, t)
509
+ if config.guidance_scale > 0.0:
510
+ x_for_grad = x.detach().requires_grad_(True)
511
+ score = utility_head(repeated_condition, x_for_grad).sum()
512
+ grad = torch.autograd.grad(score, x_for_grad, only_inputs=True)[0]
513
+ grad = _clip_gradient(grad, max_norm=float(config.guidance_grad_clip))
514
+ with torch.no_grad():
515
+ x = x + dt * velocity + float(config.guidance_scale) * dt * grad
516
+ else:
517
+ with torch.no_grad():
518
+ x = x + dt * velocity
519
+ with torch.no_grad():
520
+ scores = utility_head(repeated_condition, x)
521
+ order = torch.argsort(scores, descending=True)[:count]
522
+ decoded_code = _denormalize(x[order], stats["code_mean"], stats["code_std"])
523
+ codes = decoded_code[:, :code_dim].detach().cpu().tolist()
524
+ return [
525
+ decode_keyframe_spline(code, horizon=horizon, action_dim=action_dim)
526
+ for code in codes
527
+ ]
528
+
529
+
530
+ def _clip_gradient(grad: Any, *, max_norm: float) -> Any:
531
+ norm = grad.norm(dim=1, keepdim=True).clamp(min=1.0e-12)
532
+ scale = torch.clamp(float(max_norm) / norm, max=1.0)
533
+ return grad * scale