B111ue commited on
Commit
800c88c
·
verified ·
1 Parent(s): df6d4a3

Upload strict640x480-v2/code/train_act.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. strict640x480-v2/code/train_act.py +466 -0
strict640x480-v2/code/train_act.py ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Decentralized local-observation ACT training for RoboFactory tasks."""
2
+ import argparse
3
+ import copy
4
+ import glob
5
+ import json
6
+ import os
7
+ import random
8
+ from collections import Counter, OrderedDict, defaultdict
9
+ from pathlib import Path
10
+
11
+ import h5py
12
+ import numpy as np
13
+ import torch
14
+ import torch.nn as nn
15
+ import torch.nn.functional as F
16
+ from torch.utils.data import DataLoader, Dataset, Sampler
17
+ from torchvision.models import resnet18
18
+ from five_task_contract import task_from_path
19
+ from five_task_contract import hierarchical_item_weights
20
+
21
+
22
+ # Kept module-global deliberately so a parent process can preload a corpus and
23
+ # fork independent CUDA training children. NumPy image arrays then remain
24
+ # read-only copy-on-write pages shared by the children; ordinary one-process
25
+ # training has exactly the same semantics as before.
26
+ EPISODE_CACHE = OrderedDict()
27
+
28
+
29
+ def seed_everything(seed):
30
+ random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
31
+ torch.cuda.manual_seed_all(seed)
32
+
33
+
34
+ def _trajectories(paths, arms):
35
+ result = []
36
+ for path in paths:
37
+ with h5py.File(path, "r") as f:
38
+ for key in sorted(f.keys()):
39
+ if key.startswith("traj_"):
40
+ tr = f[key]
41
+ # A pooled 2+3-agent corpus deliberately contains both
42
+ # two-arm and three-arm episodes. Retain each local policy
43
+ # stream that actually exists, instead of requiring the
44
+ # absent panda-2 stream in two-arm demonstrations.
45
+ present = tuple(
46
+ arm for arm in arms
47
+ if f"panda-{arm}" in tr["actions"]
48
+ and f"panda-{arm}" in tr["obs"]["agent"]
49
+ and f"head_camera_agent{arm}" in tr["obs"]["sensor_data"]
50
+ )
51
+ if not present:
52
+ continue
53
+ n = min(
54
+ len(tr["actions"][f"panda-{arm}"])
55
+ for arm in present
56
+ )
57
+ n = min(
58
+ n, *(len(tr["obs"]["agent"][f"panda-{arm}"]["qpos"]) for arm in present),
59
+ )
60
+ # The source task is retained so mixed-task training can
61
+ # balance task probability despite unequal arm counts and
62
+ # episode lengths (notably LongPipelineDelivery).
63
+ # Canonical sampling label only. It is never passed to the
64
+ # policy, and fixes per-seed LPD files being mistaken for
65
+ # separate tasks by mixed-task samplers.
66
+ result.append((path, key, n, present, task_from_path(path)))
67
+ return result
68
+
69
+
70
+ def _stats(trajectories, arms):
71
+ qs, acts = [], []
72
+ for path, key, _, present, _ in trajectories:
73
+ with h5py.File(path, "r") as f:
74
+ tr = f[key]
75
+ for arm in present:
76
+ qs.append(np.asarray(tr["obs"]["agent"][f"panda-{arm}"]["qpos"], np.float32))
77
+ acts.append(np.asarray(tr["actions"][f"panda-{arm}"], np.float32))
78
+ q, a = np.concatenate(qs), np.concatenate(acts)
79
+ return {"q_mean": q.mean(0), "q_std": q.std(0).clip(1e-4),
80
+ "a_mean": a.mean(0), "a_std": a.std(0).clip(1e-4)}
81
+
82
+
83
+ class RoboFactoryACTDataset(Dataset):
84
+ def __init__(self, trajectories, arms, horizon, stats, train, *, preload=True, cache_limit=0):
85
+ self.arms, self.horizon, self.stats = tuple(arms), horizon, stats
86
+ self.cache_limit = int(cache_limit)
87
+ # Keep entire episodes together: predictable held-out demonstrations.
88
+ kept = [x for i, x in enumerate(trajectories) if (i % 10 != 0) == train]
89
+ # A/B views of one joint episode always share a split: no paired leakage.
90
+ self.items = [
91
+ (p, k, t, arm, task)
92
+ for p, k, n, present, task in kept
93
+ for arm in present
94
+ for t in range(n)
95
+ ]
96
+ self.item_tasks = [task for _, _, _, _, task in self.items]
97
+ self.item_weights = hierarchical_item_weights(kept, self.items)
98
+ self.stream_indices = defaultdict(list)
99
+ for index, (path, key, _, arm, task) in enumerate(self.items):
100
+ self.stream_indices[(path, key, arm, task)].append(index)
101
+ # This is deliberately RAM-resident. With random ACT batches, lazy episode
102
+ # caching repeatedly decompresses 20+ MB RGB trajectories for one frame.
103
+ # The host has 192 GB RAM; keeping this single-task corpus in memory turns
104
+ # that I/O bottleneck into continuous GPU training.
105
+ self.cache = EPISODE_CACHE
106
+ if preload:
107
+ for path, key, _, present, _ in kept:
108
+ for arm in present:
109
+ self._episode(path, key, arm)
110
+
111
+ def __len__(self): return len(self.items)
112
+
113
+ def _episode(self, path, key, arm):
114
+ tag = (path, key, arm)
115
+ if tag not in self.cache:
116
+ with h5py.File(path, "r") as f:
117
+ tr = f[key]
118
+ cam = tr["obs"]["sensor_data"][f"head_camera_agent{arm}"]["rgb"][:]
119
+ qpos = tr["obs"]["agent"][f"panda-{arm}"]["qpos"][:]
120
+ actions = tr["actions"][f"panda-{arm}"][:].astype(np.float32)
121
+ self.cache[tag] = (cam, qpos.astype(np.float32), actions)
122
+ if self.cache_limit > 0:
123
+ while len(self.cache) > self.cache_limit:
124
+ self.cache.popitem(last=False)
125
+ else:
126
+ self.cache.move_to_end(tag)
127
+ return self.cache[tag]
128
+
129
+ def __getitem__(self, idx):
130
+ path, key, t, arm, _ = self.items[idx]
131
+ image, qpos, actions = self._episode(path, key, arm)
132
+ # RGB observations are local to this arm only; no ID or global view.
133
+ # Keep the camera frame as uint8 until it reaches the GPU. Per-sample
134
+ # CPU resizing starves two 5090s; batched resize is done in _loss.
135
+ im = torch.from_numpy(image[t]).permute(2, 0, 1).contiguous()
136
+ q = (qpos[t] - self.stats["q_mean"]) / self.stats["q_std"]
137
+ future = actions[t:t + self.horizon]
138
+ valid = len(future)
139
+ padded = np.empty((self.horizon, actions.shape[1]), np.float32)
140
+ padded[:valid] = future
141
+ padded[valid:] = future[-1]
142
+ padded = (padded - self.stats["a_mean"]) / self.stats["a_std"]
143
+ mask = np.zeros(self.horizon, np.bool_); mask[:valid] = True
144
+ return im, torch.from_numpy(q), torch.from_numpy(padded), torch.from_numpy(mask)
145
+
146
+
147
+ class EpisodeBlockBatchSampler(Sampler):
148
+ """Task-balanced local episode blocks for bounded RGB caching."""
149
+ def __init__(self, dataset, batch_size, updates, block_updates, seed, task_balanced):
150
+ if batch_size % 4:
151
+ raise ValueError("episode-block batching requires batch size divisible by 4")
152
+ self.batch_size = batch_size
153
+ self.updates = updates
154
+ self.block_updates = block_updates
155
+ self.seed = seed
156
+ self.epoch = 0
157
+ self.per_stream = batch_size // 4
158
+ # Preserve the requested hierarchy: task -> demonstration -> local
159
+ # arm -> time. Flat stream sampling would over-represent a four-arm
160
+ # demonstration simply because it contributes four streams.
161
+ self.by_task_episode = defaultdict(lambda: defaultdict(list))
162
+ for (path, key, arm, task), indices in dataset.stream_indices.items():
163
+ self.by_task_episode[task][(path, key)].append(indices)
164
+ self.tasks = sorted(self.by_task_episode)
165
+ self.task_balanced = task_balanced
166
+ self.all_episodes = [streams for episodes in self.by_task_episode.values() for streams in episodes.values()]
167
+
168
+ def __len__(self):
169
+ return self.updates
170
+
171
+ def __iter__(self):
172
+ rng = random.Random(self.seed + self.epoch)
173
+ self.epoch += 1
174
+ produced = 0
175
+ while produced < self.updates:
176
+ episodes = self.all_episodes
177
+ if self.task_balanced:
178
+ task = self.tasks[rng.randrange(len(self.tasks))]
179
+ episodes = list(self.by_task_episode[task].values())
180
+ # Choose a demonstration first and then an arm uniformly within it.
181
+ streams = [episode[rng.randrange(len(episode))]
182
+ for episode in (episodes[rng.randrange(len(episodes))] for _ in range(4))]
183
+ for _ in range(min(self.block_updates, self.updates - produced)):
184
+ batch = [
185
+ stream[rng.randrange(len(stream))]
186
+ for stream in streams
187
+ for _ in range(self.per_stream)
188
+ ]
189
+ rng.shuffle(batch)
190
+ yield batch
191
+ produced += 1
192
+
193
+
194
+ class ACT(nn.Module):
195
+ """ACT-style CVAE with independently configurable action encoder/decoder."""
196
+ def __init__(self, state_dim, action_dim, horizon=100, d_model=384, enc_layers=4, dec_layers=7,
197
+ latent_dim=32, vision_backbone="resnet18",
198
+ dino_model="facebook/dinov3-vitb16-pretrain-lvd1689m"):
199
+ super().__init__()
200
+ self.vision_backbone = vision_backbone
201
+ self.dino_model = dino_model
202
+ if vision_backbone == "resnet18":
203
+ backbone = resnet18(weights=None)
204
+ self.vision = nn.Sequential(*list(backbone.children())[:-2])
205
+ self.vision_proj = nn.Conv2d(512, d_model, 1)
206
+ elif vision_backbone == "dinov3_vitb16_frozen":
207
+ # DINOv3 is intentionally a frozen visual head: only the ACT
208
+ # projection/transformers/policy layers receive gradients.
209
+ from transformers import AutoImageProcessor, AutoModel
210
+ token = os.environ.get("HF_TOKEN")
211
+ processor = AutoImageProcessor.from_pretrained(dino_model, token=token)
212
+ self.vision = AutoModel.from_pretrained(dino_model, token=token)
213
+ self.vision.requires_grad_(False)
214
+ self.vision.eval()
215
+ self.register_buffer("dino_mean", torch.tensor(processor.image_mean).view(1, -1, 1, 1))
216
+ self.register_buffer("dino_std", torch.tensor(processor.image_std).view(1, -1, 1, 1))
217
+ self.vision_proj = nn.Linear(self.vision.config.hidden_size, d_model)
218
+ else:
219
+ raise ValueError(f"unknown vision backbone: {vision_backbone}")
220
+ self.state = nn.Sequential(nn.Linear(state_dim, d_model), nn.GELU(), nn.Linear(d_model, d_model))
221
+ self.action = nn.Linear(action_dim, d_model)
222
+ self.pos = nn.Parameter(torch.randn(1, horizon, d_model) * .02)
223
+ self.query = nn.Parameter(torch.randn(1, horizon, d_model) * .02)
224
+ enc = nn.TransformerEncoderLayer(d_model, 8, d_model * 4, dropout=.1,
225
+ batch_first=True, norm_first=True, activation="gelu")
226
+ dec = nn.TransformerDecoderLayer(d_model, 8, d_model * 4, dropout=.1,
227
+ batch_first=True, norm_first=True, activation="gelu")
228
+ self.posterior = nn.TransformerEncoder(enc, num_layers=enc_layers)
229
+ self.decoder = nn.TransformerDecoder(dec, num_layers=dec_layers)
230
+ self.latent = nn.Linear(d_model, latent_dim * 2)
231
+ self.z_proj = nn.Linear(latent_dim, d_model)
232
+ self.out = nn.Linear(d_model, action_dim)
233
+ self.horizon = horizon
234
+
235
+ def _vision_tokens(self, image):
236
+ if self.vision_backbone == "resnet18":
237
+ image = F.interpolate(image, size=(256, 256), mode="bilinear", align_corners=False)
238
+ return self.vision_proj(self.vision(image)).flatten(2).transpose(1, 2)
239
+ # 640×480 is retained natively: both dimensions are divisible by the
240
+ # DINOv3 ViT-B/16 patch size, yielding a 40×30 local-image token grid.
241
+ if tuple(image.shape[-2:]) != (480, 640):
242
+ raise ValueError(f"strict 640x480 protocol required, got {tuple(image.shape[-2:])}")
243
+ image = (image - self.dino_mean) / self.dino_std
244
+ self.vision.eval() # model.train() must never enable frozen-head dropout
245
+ with torch.no_grad():
246
+ all_tokens = self.vision(pixel_values=image).last_hidden_state
247
+ # Drop CLS and DINO register tokens; retain exactly the 40×30
248
+ # patch grid produced by an unresized 640×480 ViT-B/16 image.
249
+ first_patch = 1 + int(getattr(self.vision.config, "num_register_tokens", 0))
250
+ tokens = all_tokens[:, first_patch:]
251
+ if tokens.shape[1] != 30 * 40:
252
+ raise ValueError(f"strict 30x40 DINO grid required, got {tokens.shape[1]} tokens")
253
+ return self.vision_proj(tokens)
254
+
255
+ def forward(self, image, qpos, actions=None):
256
+ x = self._vision_tokens(image)
257
+ state = self.state(qpos).unsqueeze(1)
258
+ if actions is not None:
259
+ h = self.posterior(self.action(actions) + self.pos)
260
+ mu, logvar = self.latent(h.mean(1)).chunk(2, -1)
261
+ z = mu + torch.randn_like(mu) * torch.exp(.5 * logvar)
262
+ else:
263
+ mu = logvar = None
264
+ z = torch.zeros((image.shape[0], self.z_proj.in_features), device=image.device)
265
+ memory = torch.cat((state, self.z_proj(z).unsqueeze(1), x), dim=1)
266
+ pred = self.out(self.decoder(self.query.expand(image.shape[0], -1, -1), memory))
267
+ return pred, mu, logvar
268
+
269
+
270
+ def _loss(model, image, qpos, actions, mask, beta):
271
+ """Return differentiable total loss plus reporting tensors for one microbatch."""
272
+ image = image.float().div_(255)
273
+ with torch.autocast("cuda", dtype=torch.bfloat16):
274
+ pred, mu, logvar = model(image, qpos, actions)
275
+ mse = ((pred - actions).square().mean(-1) * mask).sum() / mask.sum().clamp_min(1)
276
+ kl = -.5 * (1 + logvar - mu.square() - logvar.exp()).sum(-1).mean()
277
+ return mse + beta * kl, mse, kl
278
+
279
+
280
+ def _sync_to_replica(master, replica, replica_device):
281
+ """Copy the one authoritative shared-policy state to the second GPU."""
282
+ with torch.no_grad():
283
+ for src, dst in zip(master.parameters(), replica.parameters()):
284
+ dst.copy_(src.to(replica_device))
285
+ for src, dst in zip(master.buffers(), replica.buffers()):
286
+ dst.copy_(src.to(replica_device))
287
+
288
+
289
+ def _aggregate_replica_grads(master, replica, master_device):
290
+ """Sum already globally weighted replica gradients without NCCL."""
291
+ with torch.no_grad():
292
+ for p0, p1 in zip(master.parameters(), replica.parameters()):
293
+ if p0.grad is None:
294
+ p0.grad = p1.grad.to(master_device).clone()
295
+ elif p1.grad is not None:
296
+ p0.grad.add_(p1.grad.to(master_device))
297
+ # Keep BatchNorm running statistics representative of both local halves.
298
+ for b0, b1 in zip(master.buffers(), replica.buffers()):
299
+ if b0.is_floating_point():
300
+ b0.add_(b1.to(master_device)).mul_(0.5)
301
+
302
+
303
+ def epoch(model, loader, opt, device, beta, max_updates=None, scheduler=None, replica=None, replica_device=None):
304
+ training = opt is not None
305
+ model.train(training)
306
+ total = {"loss": 0., "mse": 0., "kl": 0., "n": 0}
307
+ ctx = torch.enable_grad if training else torch.no_grad
308
+ updates = 0
309
+ with ctx():
310
+ for image, qpos, actions, mask in loader:
311
+ # A second replica receives the other half of the *global* batch.
312
+ # This is manual synchronous data parallelism, needed because this
313
+ # Vast host cannot bootstrap NCCL even though both CUDA devices work.
314
+ use_replica = replica is not None and image.shape[0] >= 2
315
+ if use_replica:
316
+ split = image.shape[0] // 2
317
+ first = tuple(x[:split].to(device, non_blocking=True) for x in (image, qpos, actions, mask))
318
+ second = tuple(x[split:].to(replica_device, non_blocking=True) for x in (image, qpos, actions, mask))
319
+ loss0, mse0, kl0 = _loss(model, *first, beta)
320
+ loss1, mse1, kl1 = _loss(replica, *second, beta)
321
+ action_weight0 = float(first[3].sum().item())
322
+ action_weight1 = float(second[3].sum().item())
323
+ action_total = max(action_weight0 + action_weight1, 1.)
324
+ sample_total = float(image.shape[0])
325
+ # Weight gradients exactly as the loss over the unsharded batch.
326
+ # Metrics live on the master GPU only. The actual backward below
327
+ # stays separate on each GPU and never needs a cross-device graph.
328
+ mse = mse0.detach() * (action_weight0 / action_total) + mse1.detach().to(device) * (action_weight1 / action_total)
329
+ kl = kl0.detach() * (first[0].shape[0] / sample_total) + kl1.detach().to(device) * (second[0].shape[0] / sample_total)
330
+ loss = mse + beta * kl
331
+ n = image.shape[0]
332
+ else:
333
+ image, qpos, actions, mask = (x.to(device, non_blocking=True) for x in (image, qpos, actions, mask))
334
+ loss, mse, kl = _loss(model, image, qpos, actions, mask, beta)
335
+ n = image.shape[0]
336
+ if training:
337
+ opt.zero_grad(set_to_none=True)
338
+ if use_replica:
339
+ for p in replica.parameters(): p.grad = None
340
+ # Backpropagate weighted local terms before averaging.
341
+ loss0w = mse0 * (action_weight0 / action_total) + beta * kl0 * (first[0].shape[0] / sample_total)
342
+ loss1w = mse1 * (action_weight1 / action_total) + beta * kl1 * (second[0].shape[0] / sample_total)
343
+ loss0w.backward(); loss1w.backward()
344
+ _aggregate_replica_grads(model, replica, device)
345
+ else:
346
+ loss.backward()
347
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.)
348
+ opt.step()
349
+ if use_replica: _sync_to_replica(model, replica, replica_device)
350
+ if scheduler is not None: scheduler.step()
351
+ updates += 1
352
+ for k, v in (("loss", loss), ("mse", mse), ("kl", kl)):
353
+ total[k] += float(v.detach()) * n
354
+ total["n"] += n
355
+ if training and max_updates is not None and updates >= max_updates:
356
+ break
357
+ return ({k: v / total["n"] for k, v in total.items() if k != "n"}, updates)
358
+
359
+
360
+ def main():
361
+ p = argparse.ArgumentParser()
362
+ p.add_argument("--data", required=True, help="Glob or comma-separated HDF5 paths")
363
+ p.add_argument("--arm", type=int, choices=(0, 1), help="single-arm ablation only")
364
+ p.add_argument("--shared", action="store_true", help="pool listed agents' local data into one shared policy")
365
+ p.add_argument("--shared-arms", default="0,1", help="comma-separated agents for --shared, e.g. 0,1,2")
366
+ p.add_argument("--devices", default="0", help="one shared DataParallel model, e.g. 0,1")
367
+ p.add_argument("--output", required=True)
368
+ p.add_argument("--horizon", type=int, default=100)
369
+ p.add_argument("--enc-layers", type=int, default=4)
370
+ p.add_argument("--dec-layers", type=int, default=7)
371
+ p.add_argument("--d-model", type=int, default=384)
372
+ p.add_argument("--vision-backbone", choices=("resnet18", "dinov3_vitb16_frozen"), default="resnet18")
373
+ p.add_argument("--dino-model", default="facebook/dinov3-vitb16-pretrain-lvd1689m")
374
+ p.add_argument("--camera-width", type=int, default=320)
375
+ p.add_argument("--camera-height", type=int, default=240)
376
+ p.add_argument("--batch-size", type=int, default=128)
377
+ p.add_argument("--updates", type=int, default=60000)
378
+ p.add_argument("--save-updates", default="20000,40000,60000",
379
+ help="comma-separated exact optimizer-update checkpoints")
380
+ p.add_argument("--workers", type=int, default=8)
381
+ p.add_argument("--lazy-cache-episodes", type=int, default=0,
382
+ help="Bound RGB cache and use episode-block batches (0 keeps full preloading).")
383
+ p.add_argument("--episode-block-updates", type=int, default=64,
384
+ help="Updates reusing four local streams in lazy-cache mode.")
385
+ p.add_argument("--task-balanced", action="store_true",
386
+ help="Sample each source task equally in mixed-task training.")
387
+ p.add_argument("--lr", type=float, default=2e-4)
388
+ p.add_argument("--beta", type=float, default=1e-3)
389
+ p.add_argument("--seed", type=int, default=2026)
390
+ a = p.parse_args()
391
+ assert a.shared != (a.arm is not None), "set exactly one of --shared or --arm"
392
+ arms = tuple(int(x) for x in a.shared_arms.split(",")) if a.shared else (a.arm,)
393
+ assert arms and len(set(arms)) == len(arms) and all(x >= 0 for x in arms)
394
+ seed_everything(a.seed); torch.backends.cudnn.benchmark = True
395
+ device_ids = [int(x) for x in a.devices.split(",")]
396
+ device = torch.device(f"cuda:{device_ids[0]}")
397
+ paths = sorted({p for item in a.data.split(",") for p in glob.glob(item)})
398
+ assert paths, f"no HDF5 files match {a.data}"
399
+ tr = _trajectories(paths, arms); assert len(tr) >= 10, "need at least 10 successful demonstrations"
400
+ stats = _stats(tr, arms)
401
+ lazy_cache = a.lazy_cache_episodes > 0
402
+ if lazy_cache and a.workers:
403
+ raise ValueError("lazy RGB cache requires --workers 0")
404
+ train = RoboFactoryACTDataset(tr, arms, a.horizon, stats, True,
405
+ preload=not lazy_cache, cache_limit=a.lazy_cache_episodes)
406
+ valid = RoboFactoryACTDataset(tr, arms, a.horizon, stats, False,
407
+ preload=not lazy_cache, cache_limit=a.lazy_cache_episodes)
408
+ kwargs = dict(batch_size=a.batch_size, num_workers=a.workers, pin_memory=True,
409
+ persistent_workers=a.workers > 0)
410
+ # Forking workers after CUDA is initialized can deadlock (and h5py is not
411
+ # fork-friendly either). Spawn keeps the two GPU training jobs independent.
412
+ if a.workers > 0:
413
+ kwargs["multiprocessing_context"] = "spawn"
414
+ sampler = None
415
+ if lazy_cache:
416
+ sampler = EpisodeBlockBatchSampler(train, a.batch_size, a.updates,
417
+ a.episode_block_updates, a.seed, a.task_balanced)
418
+ train_loader = DataLoader(train, batch_sampler=sampler, num_workers=0, pin_memory=True)
419
+ elif a.task_balanced:
420
+ counts = Counter(train.item_tasks)
421
+ if len(counts) > 1:
422
+ weights = torch.as_tensor(train.item_weights, dtype=torch.double)
423
+ sampler = torch.utils.data.WeightedRandomSampler(weights, num_samples=len(weights), replacement=True)
424
+ if not lazy_cache:
425
+ train_loader = DataLoader(train, shuffle=sampler is None, sampler=sampler, drop_last=True, **kwargs)
426
+ val_loader = DataLoader(valid, shuffle=False, **kwargs)
427
+ sample = train[0]
428
+ if tuple(sample[0].shape[-2:]) != (a.camera_height, a.camera_width):
429
+ raise ValueError(f"dataset frame {tuple(sample[0].shape[-2:])} does not match requested "
430
+ f"{a.camera_height}x{a.camera_width}")
431
+ model = ACT(len(sample[1]), len(sample[2][0]), a.horizon, a.d_model, a.enc_layers, a.dec_layers,
432
+ vision_backbone=a.vision_backbone, dino_model=a.dino_model).to(device)
433
+ replica = None; replica_device = None
434
+ if len(device_ids) > 1:
435
+ assert len(device_ids) == 2, "manual synchronous mode currently supports exactly two GPUs"
436
+ replica_device = torch.device(f"cuda:{device_ids[1]}")
437
+ replica = copy.deepcopy(model).to(replica_device)
438
+ opt = torch.optim.AdamW(model.parameters(), lr=a.lr, weight_decay=1e-4)
439
+ sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, a.updates)
440
+ out = Path(a.output); out.mkdir(parents=True, exist_ok=True)
441
+ np.savez(out / "normalization.npz", **stats)
442
+ best = float("inf")
443
+ info = vars(a) | {"arms": arms, "files": paths, "episodes": len(tr), "train_steps": len(train), "val_steps": len(valid),
444
+ "train_task_item_counts": dict(Counter(train.item_tasks)),
445
+ "state_dim": len(sample[1]), "action_dim": len(sample[2][0])}
446
+ (out / "config.json").write_text(json.dumps(info, indent=2))
447
+ milestones = {int(x) for x in a.save_updates.split(",") if x}
448
+ updates = 0; e = 0
449
+ while updates < a.updates:
450
+ e += 1
451
+ next_stop = min([a.updates] + [m for m in milestones if m > updates])
452
+ train_metrics, ran = epoch(model, train_loader, opt, device, a.beta, next_stop - updates, sched, replica, replica_device)
453
+ updates += ran
454
+ val_metrics, _ = epoch(model, val_loader, None, device, a.beta, replica=replica, replica_device=replica_device)
455
+ report = {"epoch": e, "updates": updates, "lr": sched.get_last_lr()[0], "train": train_metrics, "val": val_metrics}
456
+ print(json.dumps(report), flush=True)
457
+ state = {"model": model.state_dict(), "optimizer": opt.state_dict(), "epoch": e,
458
+ "updates": updates, "stats": stats, "config": info}
459
+ torch.save(state, out / "last.pt")
460
+ if val_metrics["loss"] < best:
461
+ best = val_metrics["loss"]; torch.save(state, out / "best.pt")
462
+ if updates in milestones:
463
+ torch.save(state, out / f"checkpoint_{updates:06d}.pt")
464
+
465
+
466
+ if __name__ == "__main__": main()