AlexWortega commited on
Commit
d9b76b2
·
verified ·
1 Parent(s): e23d6d9

train_fast: v4 all-channels via hub stream (support passthrough, morph_text tokenization, guarded shard morph block)

Browse files
Files changed (1) hide show
  1. tinyvla_b200/scripts/train_fast.py +98 -14
tinyvla_b200/scripts/train_fast.py CHANGED
@@ -75,17 +75,29 @@ def load_compatible(model, path: Path):
75
 
76
  sd = load_file(path / "model.safetensors")
77
  own = model.state_dict()
78
- keep, reshaped, unexpected = {}, [], []
79
  for k, v in sd.items():
80
  if k not in own:
81
  unexpected.append(k)
82
  elif own[k].shape != v.shape:
83
- reshaped.append((k, tuple(v.shape), tuple(own[k].shape)))
 
 
 
 
 
 
 
 
 
 
84
  else:
85
  keep[k] = v
86
  missing = [k for k in own if k not in keep]
87
  model.load_state_dict(keep, strict=False)
88
  print(f"resume {path}: loaded {len(keep)}/{len(own)} tensors")
 
 
89
  for k, a, b in reshaped:
90
  print(f" RE-INIT (shape changed) {k}: {a} -> {b}")
91
  if unexpected:
@@ -107,11 +119,13 @@ class Collate:
107
  dataloaders in testing; spawned workers start clean.
108
  """
109
 
110
- def __init__(self, model_name: str, max_length: int):
111
  self.model_name = model_name
112
  self.max_length = max_length
 
113
  self._tokenizer = None
114
  self._cache: dict = {}
 
115
 
116
  def _tok(self, tasks):
117
  if self._tokenizer is None:
@@ -130,19 +144,38 @@ class Collate:
130
  return (torch.stack([self._cache[t][0] for t in tasks]),
131
  torch.stack([self._cache[t][1] for t in tasks]))
132
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  def __getstate__(self):
134
- return {"model_name": self.model_name, "max_length": self.max_length}
 
135
 
136
  def __setstate__(self, st):
137
- self.__init__(st["model_name"], st["max_length"])
138
 
139
  def __call__(self, items):
140
  out = {}
141
  for k in items[0]:
 
 
142
  if k == "task":
143
  ids, mask = self._tok([it["task"] for it in items])
144
  out["observation.language.tokens"] = ids
145
  out["observation.language.attention_mask"] = mask
 
 
 
 
146
  else:
147
  out[k] = torch.stack([it[k] for it in items])
148
  return out
@@ -180,10 +213,18 @@ def main():
180
  print(*a, **k)
181
 
182
  dev = torch.device("cuda", local_rank if ddp else 0)
 
 
 
 
 
 
 
183
 
184
  src_cfg = cfg["source"]
185
  morph = None
186
- if cfg.get("morphology_descriptors") and cfg["policy"].get("conditioning") == "morph":
 
187
  from tinyvla.modules.embodiment import MORPH_FIELDS
188
 
189
  raw = yaml.safe_load(Path(cfg["morphology_descriptors"]).read_text())
@@ -202,19 +243,59 @@ def main():
202
 
203
  specs = yaml.safe_load(Path(src_cfg["specs"]).read_text())["datasets"]
204
  tok_path = _os.path.expanduser("~/.cache/huggingface/token")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
  source = HubEpisodeStream(
206
  specs,
207
  token=open(tok_path).read().strip() if _os.path.exists(tok_path) else None,
208
  chunk=chunk,
209
- image_size=cfg["policy"].get("image_size", 256),
210
- max_state_dim=cfg["policy"]["max_state_dim"],
211
- max_action_dim=cfg["policy"]["max_action_dim"],
212
  shuffle_buffer=cfg.get("shuffle_buffer", 4096),
213
  seed=cfg.get("seed", 42),
214
  rank=rank,
215
  world_size=world,
 
 
 
216
  )
217
  log(f"source: HUB STREAM, {len(specs)} datasets (infinite mixture), world={world}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
  else:
219
  from tinyvla.data.shards import ShardSource
220
 
@@ -235,7 +316,7 @@ def main():
235
  log(f"source: {source.num_frames:,} frames @ {source.fps} Hz, "
236
  f"state {source.state_dim}d action {source.action_dim}d, {len(source.shards)} shards")
237
 
238
- if src_cfg.get("type") == "hub":
239
  # per-dataset dims vary; the source pads everything to the config caps
240
  policy, pcfg = make_policy(cfg, cfg["policy"]["max_state_dim"], cfg["policy"]["max_action_dim"])
241
  else:
@@ -257,7 +338,8 @@ def main():
257
  )
258
 
259
  # ---- pre-tokenize every distinct instruction once -----------------------
260
- collate = Collate(pcfg.lm_model_name, pcfg.tokenizer_max_length)
 
261
 
262
  nw = cfg.get("num_workers", 12)
263
  if ddp:
@@ -328,12 +410,14 @@ def main():
328
  batch = next(data_iter)
329
  batch = {k: (v.to(dev, non_blocking=True) if torch.is_tensor(v) else v)
330
  for k, v in batch.items()}
331
- with torch.autocast("cuda", dtype=torch.bfloat16):
332
  loss, info = policy(batch)
333
- (loss / grad_accum).backward()
334
  seen += cfg["batch_size"]
 
335
  torch.nn.utils.clip_grad_norm_(raw_policy.parameters(), cfg.get("grad_clip", 10.0))
336
- opt.step()
 
337
  sched.step()
338
  step += 1
339
 
 
75
 
76
  sd = load_file(path / "model.safetensors")
77
  own = model.state_dict()
78
+ keep, reshaped, expanded, unexpected = {}, [], [], []
79
  for k, v in sd.items():
80
  if k not in own:
81
  unexpected.append(k)
82
  elif own[k].shape != v.shape:
83
+ # Rows grew, trailing dims intact (num_embodiments 16 -> 32): keep
84
+ # the trained rows, new rows stay at init. A plain re-init here
85
+ # would silently discard every trained embodiment embedding.
86
+ if (own[k].ndim == v.ndim and own[k].shape[0] > v.shape[0]
87
+ and own[k].shape[1:] == v.shape[1:]):
88
+ merged = own[k].clone()
89
+ merged[: v.shape[0]] = v
90
+ keep[k] = merged
91
+ expanded.append((k, tuple(v.shape), tuple(own[k].shape)))
92
+ else:
93
+ reshaped.append((k, tuple(v.shape), tuple(own[k].shape)))
94
  else:
95
  keep[k] = v
96
  missing = [k for k in own if k not in keep]
97
  model.load_state_dict(keep, strict=False)
98
  print(f"resume {path}: loaded {len(keep)}/{len(own)} tensors")
99
+ for k, a, b in expanded:
100
+ print(f" EXPANDED (rows grew, old rows kept) {k}: {a} -> {b}")
101
  for k, a, b in reshaped:
102
  print(f" RE-INIT (shape changed) {k}: {a} -> {b}")
103
  if unexpected:
 
119
  dataloaders in testing; spawned workers start clean.
120
  """
121
 
122
+ def __init__(self, model_name: str, max_length: int, morph_text_max_len: int = 32):
123
  self.model_name = model_name
124
  self.max_length = max_length
125
+ self.morph_text_max_len = morph_text_max_len
126
  self._tokenizer = None
127
  self._cache: dict = {}
128
+ self._mcache: dict = {}
129
 
130
  def _tok(self, tasks):
131
  if self._tokenizer is None:
 
144
  return (torch.stack([self._cache[t][0] for t in tasks]),
145
  torch.stack([self._cache[t][1] for t in tasks]))
146
 
147
+ def _mtok(self, texts):
148
+ if self._tokenizer is None:
149
+ self._tok([""]) # init tokenizer
150
+ new = [t for t in set(texts) if t not in self._mcache]
151
+ if new:
152
+ e = self._tokenizer(new, padding="max_length", truncation=True,
153
+ max_length=self.morph_text_max_len, return_tensors="pt")
154
+ for i, t in enumerate(new):
155
+ self._mcache[t] = (e["input_ids"][i], e["attention_mask"][i].bool())
156
+ return (torch.stack([self._mcache[t][0] for t in texts]),
157
+ torch.stack([self._mcache[t][1] for t in texts]))
158
+
159
  def __getstate__(self):
160
+ return {"model_name": self.model_name, "max_length": self.max_length,
161
+ "morph_text_max_len": self.morph_text_max_len}
162
 
163
  def __setstate__(self, st):
164
+ self.__init__(st["model_name"], st["max_length"], st.get("morph_text_max_len", 32))
165
 
166
  def __call__(self, items):
167
  out = {}
168
  for k in items[0]:
169
+ if k.startswith("__"):
170
+ continue # webdataset re-injects __key__/__url__ after every stage
171
  if k == "task":
172
  ids, mask = self._tok([it["task"] for it in items])
173
  out["observation.language.tokens"] = ids
174
  out["observation.language.attention_mask"] = mask
175
+ elif k == "morph_text":
176
+ ids, mask = self._mtok([it["morph_text"] for it in items])
177
+ out["morph_text_ids"] = ids
178
+ out["morph_text_mask"] = mask
179
  else:
180
  out[k] = torch.stack([it[k] for it in items])
181
  return out
 
213
  print(*a, **k)
214
 
215
  dev = torch.device("cuda", local_rank if ddp else 0)
216
+ # V100 (sm70) has no bf16: fall back to fp16 + GradScaler so debug runs on
217
+ # older cards work; H100/B200 keep bf16 with the scaler disabled (no-op).
218
+ # including_emulation=False: plain is_bf16_supported() returns True on
219
+ # Volta (software emulation) and silently makes training ~10x slower.
220
+ _bf16 = torch.cuda.is_bf16_supported(including_emulation=False)
221
+ amp_dtype = torch.bfloat16 if _bf16 else torch.float16
222
+ scaler = torch.amp.GradScaler("cuda", enabled=amp_dtype is torch.float16)
223
 
224
  src_cfg = cfg["source"]
225
  morph = None
226
+ if (src_cfg.get("type") != "hub" and cfg.get("morphology_descriptors")
227
+ and cfg["policy"].get("conditioning") == "morph"):
228
  from tinyvla.modules.embodiment import MORPH_FIELDS
229
 
230
  raw = yaml.safe_load(Path(cfg["morphology_descriptors"]).read_text())
 
243
 
244
  specs = yaml.safe_load(Path(src_cfg["specs"]).read_text())["datasets"]
245
  tok_path = _os.path.expanduser("~/.cache/huggingface/token")
246
+ pol = cfg["policy"]
247
+ n_support = pol.get("n_support", 0) if (pol.get("use_demo_conditioning") or pol.get("vlm_native")) else 0
248
+ morph_map, prompt_map = {}, {}
249
+ if cfg.get("morphology_descriptors"):
250
+ from tinyvla.modules.embodiment import MORPH_FIELDS
251
+
252
+ raw = yaml.safe_load(Path(cfg["morphology_descriptors"]).read_text())
253
+ sc = {"arm_dof": 0.1, "reach_m": 2, "gripper_width_m": 10, "num_cameras": 1 / 3,
254
+ "control_hz": 1 / 30, "joint_lo_mean": 1 / 3.1416, "joint_hi_mean": 1 / 3.1416,
255
+ "workspace_x": 2, "workspace_y": 2, "workspace_z": 2, "payload_kg": 0.2}
256
+ for krobot, d in raw.items():
257
+ morph_map[krobot] = torch.tensor([d.get(f, 0) * sc.get(f, 1) for f in MORPH_FIELDS],
258
+ dtype=torch.float32)
259
+ if cfg.get("robot_prompts"):
260
+ prompt_map = yaml.safe_load(Path(cfg["robot_prompts"]).read_text())
261
  source = HubEpisodeStream(
262
  specs,
263
  token=open(tok_path).read().strip() if _os.path.exists(tok_path) else None,
264
  chunk=chunk,
265
+ image_size=pol.get("image_size", 256),
266
+ max_state_dim=pol["max_state_dim"],
267
+ max_action_dim=pol["max_action_dim"],
268
  shuffle_buffer=cfg.get("shuffle_buffer", 4096),
269
  seed=cfg.get("seed", 42),
270
  rank=rank,
271
  world_size=world,
272
+ n_support=n_support,
273
+ morph_descriptors=morph_map,
274
+ robot_prompts=prompt_map,
275
  )
276
  log(f"source: HUB STREAM, {len(specs)} datasets (infinite mixture), world={world}")
277
+ elif src_cfg.get("type") == "wds":
278
+ # local self-contained webdataset tars (pack_wds.py / *_to_wds.py output),
279
+ # mixed per-sample by weight; instructions resolved from tasks.json
280
+ from tinyvla.data.wds_mix import MixtureSource
281
+
282
+ specs = yaml.safe_load(Path(src_cfg["specs"]).read_text())["datasets"]
283
+ root = Path(src_cfg.get("root", "."))
284
+ for s in specs:
285
+ if "dir" not in s: # hf_repo: fetched beforehand by scripts/fetch_wds.py
286
+ s["dir"] = str(root / s["hf_repo"].split("/")[-1] / s.get("subdir", ""))
287
+ source = MixtureSource(
288
+ specs,
289
+ batch_size=cfg["batch_size"],
290
+ num_workers=cfg.get("num_workers", 12),
291
+ image_size=cfg["policy"].get("image_size", 256),
292
+ max_state_dim=cfg["policy"]["max_state_dim"],
293
+ max_action_dim=cfg["policy"]["max_action_dim"],
294
+ shuffle_buffer=cfg.get("shuffle_buffer", 4096),
295
+ steps_per_epoch=cfg.get("steps_per_epoch", 1000),
296
+ seed=cfg.get("seed", 42) + rank, # decorrelate ranks: resampled streams
297
+ )
298
+ log(f"source: WDS MIX, {len(specs)} datasets (infinite mixture), world={world}")
299
  else:
300
  from tinyvla.data.shards import ShardSource
301
 
 
316
  log(f"source: {source.num_frames:,} frames @ {source.fps} Hz, "
317
  f"state {source.state_dim}d action {source.action_dim}d, {len(source.shards)} shards")
318
 
319
+ if src_cfg.get("type") in ("hub", "wds"):
320
  # per-dataset dims vary; the source pads everything to the config caps
321
  policy, pcfg = make_policy(cfg, cfg["policy"]["max_state_dim"], cfg["policy"]["max_action_dim"])
322
  else:
 
338
  )
339
 
340
  # ---- pre-tokenize every distinct instruction once -----------------------
341
+ collate = Collate(pcfg.lm_model_name, pcfg.tokenizer_max_length,
342
+ getattr(pcfg, "morph_text_max_len", 32))
343
 
344
  nw = cfg.get("num_workers", 12)
345
  if ddp:
 
410
  batch = next(data_iter)
411
  batch = {k: (v.to(dev, non_blocking=True) if torch.is_tensor(v) else v)
412
  for k, v in batch.items()}
413
+ with torch.autocast("cuda", dtype=amp_dtype):
414
  loss, info = policy(batch)
415
+ scaler.scale(loss / grad_accum).backward()
416
  seen += cfg["batch_size"]
417
+ scaler.unscale_(opt)
418
  torch.nn.utils.clip_grad_norm_(raw_policy.parameters(), cfg.get("grad_clip", 10.0))
419
+ scaler.step(opt)
420
+ scaler.update()
421
  sched.step()
422
  step += 1
423