-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathgroot_rtx.py
More file actions
1876 lines (1622 loc) · 81.4 KB
/
Copy pathgroot_rtx.py
File metadata and controls
1876 lines (1622 loc) · 81.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""FlashRT -- RTX GROOT N1.6 torch frontend.
Loads HuggingFace GR00T-N1.6-3B safetensors checkpoints and drives the
framework-agnostic ``GrootSigLIP2`` / ``GrootQwen3`` / ``GrootDiT`` classes
in :mod:`flash_rt.models.groot.pipeline_rtx`.
Usage::
from flash_rt.hardware.rtx import GrootTorchFrontendRtx
pipe = GrootTorchFrontendRtx(
"/path/to/GR00T-N1.6-3B",
num_views=2,
embodiment_tag="libero_panda",
)
pipe.set_prompt("pick up the red block")
out = pipe.infer({
"image": img1, # numpy uint8 (224, 224, 3)
"wrist_image": img2,
"state": np.zeros(state_dim, dtype=np.float32),
})
actions = out["actions"] # numpy (action_horizon, action_dim)
The 3 sub-pipelines (vision, qwen3, dit) each get their own CUDA Graph,
matching the validated Thor design (and Pi0.5 rtx where the whole thing
fits in one graph).
"""
from __future__ import annotations
import ctypes
import json
import logging
import math
import pathlib
import time
from typing import Optional, Union
import numpy as np
import torch
import torch.nn.functional as F
from flash_rt.hardware.rtx.attn_backend_groot import RtxFlashAttnBackendGroot
from flash_rt.models.groot.pipeline_rtx import (
GrootDiT,
GrootQwen3,
GrootSigLIP2,
DIT_D,
DIT_H,
DIT_HD,
DIT_L,
DIT_NH,
DIT_OUTPUT_DIM,
QWEN3_D,
QWEN3_H,
QWEN3_HD,
QWEN3_L,
QWEN3_NHKV,
QWEN3_NHQ,
QWEN3_QKV_DIM,
VIS_D,
VIS_H,
VIS_HD,
VIS_L,
VIS_MLP1_IN,
VIS_NH,
VIS_PATCH_FLAT,
VIS_SPV,
VIS_SPV_RAW,
NUM_FLOW_STEPS,
ACTION_DIM,
STATE_DIM,
ACTION_HORIZON_MAX,
)
logger = logging.getLogger(__name__)
fp16 = torch.float16
fp8 = torch.float8_e4m3fn
# ── GROOT N1.6 checkpoint key prefixes ──
VIS_PREFIX = "backbone.model.vision_model.vision_model"
LLM_PREFIX = "backbone.model.language_model.model"
MLP1_PREFIX = "backbone.model.mlp1"
DIT_PREFIX = "action_head.model"
AH_PREFIX = "action_head"
# ── Embodiment id mapping (shared between Thor and rtx, see
# flash_rt/hardware/groot_embodiments.py) ──
from flash_rt.models.groot.embodiments import (
EMBODIMENT_TAG_TO_INDEX,
PUBLIC_TRAINED_TAGS,
is_embodiment_trained,
)
def _quant_fp8(w: torch.Tensor) -> tuple[torch.Tensor, float]:
"""Per-tensor FP8 E4M3 quantization."""
a = float(w.float().abs().max().item())
s = max(a / 448.0, 1e-12)
return (w.float() / s).clamp(-448, 448).to(fp8), s
# ════════════════════════════════════════════════════════════════════
# FP8 calibration — inline (was models/groot/calibration.py)
# ════════════════════════════════════════════════════════════════════
_FP8_MAX = 448.0
_SCALE_FLOOR = 1e-12
def _cal_scale(amax: float) -> float:
return max(float(amax), _SCALE_FLOOR) / _FP8_MAX
def _load_groot_calibration(checkpoint_path, Se: int) -> Optional[dict]:
"""Return cached GROOT calibration for (checkpoint, Se) or None."""
from flash_rt.core.quant.calibrator import _checkpoint_hash, _cache_path
try:
ckpt_hash = _checkpoint_hash(str(checkpoint_path))
except FileNotFoundError:
return None
cache_file = _cache_path(ckpt_hash, Se)
if not cache_file.exists():
return None
try:
with open(cache_file) as f:
data = json.load(f)
except (OSError, json.JSONDecodeError) as e:
logger.warning("Failed to read calibration cache %s: %s", cache_file, e)
return None
if data.get("ckpt_hash") != ckpt_hash or data.get("Se") != Se:
return None
return data
def _save_groot_calibration(checkpoint_path, Se: int,
qwen3_scales=None, dit_scales=None) -> None:
"""Merge the given scales into the GROOT calibration cache file."""
from flash_rt.core.quant.calibrator import _checkpoint_hash, _cache_path
ckpt_hash = _checkpoint_hash(str(checkpoint_path))
cache_file = _cache_path(ckpt_hash, Se)
cache_file.parent.mkdir(parents=True, exist_ok=True)
data: dict = {}
if cache_file.exists():
try:
with open(cache_file) as f:
data = json.load(f)
except (OSError, json.JSONDecodeError):
data = {}
data.setdefault("version", 1)
data["ckpt_hash"] = ckpt_hash
data["Se"] = Se
if qwen3_scales is not None:
data["qwen3_act_scales"] = [float(x) for x in qwen3_scales]
if dit_scales is not None:
data["dit_act_scales"] = [float(x) for x in dit_scales]
with open(cache_file, "w") as f:
json.dump(data, f, indent=2)
logger.info("Saved GROOT calibration to %s", cache_file)
def _build_rope_torch(Se: int, HD: int, theta: float = 1e6):
"""Build Qwen3 RoPE cos/sin tables."""
freqs = 1.0 / (theta ** (torch.arange(0, HD, 2, dtype=torch.float64) / HD))
pos = torch.arange(Se, dtype=torch.float64)
angles = pos[:, None] * freqs[None, :]
cos = torch.cat([angles.cos(), angles.cos()], dim=-1).to(fp16).cuda()
sin = torch.cat([angles.sin(), angles.sin()], dim=-1).to(fp16).cuda()
return cos, sin
def _calibrate_qwen3_collect_amax(sd, gemm, fvk, qwen3, ie_fp16, stream=0):
"""FP16 shadow forward through Qwen3, returns 3*L raw activation amax.
Stateless: each call processes one sample and returns its raw amax
list (no FP8 scale conversion). Use ``_calibrate_qwen3_per_sample``
to stack N calls for multi-sample calibration, or
``_calibrate_qwen3_impl`` for the legacy single-sample scale path.
"""
Se = qwen3.Se
D, H, L = QWEN3_D, QWEN3_H, QWEN3_L
NHQ, NHKV, HD = QWEN3_NHQ, QWEN3_NHKV, QWEN3_HD
QKV = QWEN3_QKV_DIM
prefix = f"{LLM_PREFIX}.layers"
w_ln, w_ln2 = [], []
w_qkv, w_qn, w_kn, w_o = [], [], [], []
w_gu, w_dn = [], []
for i in range(L):
lp = f"{prefix}.{i}"
w_ln.append(sd[f"{lp}.input_layernorm.weight"].to(fp16).contiguous())
w_ln2.append(sd[f"{lp}.post_attention_layernorm.weight"].to(fp16).contiguous())
q_w = sd[f"{lp}.self_attn.q_proj.weight"]
k_w = sd[f"{lp}.self_attn.k_proj.weight"]
v_w = sd[f"{lp}.self_attn.v_proj.weight"]
w_qkv.append(torch.cat([q_w, k_w, v_w], dim=0).T.contiguous().to(fp16))
w_qn.append(sd[f"{lp}.self_attn.q_norm.weight"].to(fp16).contiguous())
w_kn.append(sd[f"{lp}.self_attn.k_norm.weight"].to(fp16).contiguous())
w_o.append(sd[f"{lp}.self_attn.o_proj.weight"].T.contiguous().to(fp16))
g_w = sd[f"{lp}.mlp.gate_proj.weight"]
u_w = sd[f"{lp}.mlp.up_proj.weight"]
w_gu.append(torch.cat([g_w, u_w], dim=0).T.contiguous().to(fp16))
w_dn.append(sd[f"{lp}.mlp.down_proj.weight"].T.contiguous().to(fp16))
cos_full, sin_full = _build_rope_torch(max(Se, 1024), HD)
cos_r = cos_full[:Se].unsqueeze(1)
sin_r = sin_full[:Se].unsqueeze(1)
def rotate_half(t):
half = t.shape[-1] // 2
return torch.cat([-t[..., half:], t[..., :half]], dim=-1)
x = ie_fp16[:Se].clone().contiguous()
xn = torch.empty_like(x)
amax_list = []
for i in range(L):
fvk.rms_norm_fp16(
x.data_ptr(), w_ln[i].data_ptr(), xn.data_ptr(),
Se, D, 1e-6, stream)
torch.cuda.synchronize()
amax_list.append(float(xn[:Se].float().abs().max().item()))
qkv = torch.empty(Se, QKV, dtype=fp16, device="cuda")
gemm.fp16_nn(
xn.data_ptr(), w_qkv[i].data_ptr(), qkv.data_ptr(),
Se, QKV, D, stream)
Q = qkv[:, :NHQ * HD].contiguous().view(Se, NHQ, HD)
K = qkv[:, NHQ * HD:NHQ * HD + NHKV * HD].contiguous().view(Se, NHKV, HD)
V = qkv[:, NHQ * HD + NHKV * HD:].contiguous().view(Se, NHKV, HD)
fvk.rms_norm_fp16(Q.data_ptr(), w_qn[i].data_ptr(), Q.data_ptr(),
Se * NHQ, HD, 1e-6, stream)
fvk.rms_norm_fp16(K.data_ptr(), w_kn[i].data_ptr(), K.data_ptr(),
Se * NHKV, HD, 1e-6, stream)
torch.cuda.synchronize()
Qf, Kf = Q.float(), K.float()
Q = (Qf * cos_r + rotate_half(Qf) * sin_r).to(fp16)
K = (Kf * cos_r + rotate_half(Kf) * sin_r).to(fp16)
q_s = Q.unsqueeze(0).transpose(1, 2)
k_s = K.unsqueeze(0).transpose(1, 2).repeat_interleave(NHQ // NHKV, dim=1)
v_s = V.to(fp16).unsqueeze(0).transpose(1, 2).repeat_interleave(NHQ // NHKV, dim=1)
attn = F.scaled_dot_product_attention(q_s, k_s, v_s)
attn_flat = attn.transpose(1, 2).reshape(Se, D).to(fp16).contiguous()
o_out = torch.empty(Se, D, dtype=fp16, device="cuda")
gemm.fp16_nn(attn_flat.data_ptr(), w_o[i].data_ptr(), o_out.data_ptr(),
Se, D, D, stream)
fvk.residual_add_fp16(x.data_ptr(), o_out.data_ptr(), Se * D, stream)
fvk.rms_norm_fp16(x.data_ptr(), w_ln2[i].data_ptr(), xn.data_ptr(),
Se, D, 1e-6, stream)
torch.cuda.synchronize()
amax_list.append(float(xn[:Se].float().abs().max().item()))
gu = torch.empty(Se, 2 * H, dtype=fp16, device="cuda")
gemm.fp16_nn(xn.data_ptr(), w_gu[i].data_ptr(), gu.data_ptr(),
Se, 2 * H, D, stream)
gate = gu[:, :H].contiguous()
up = gu[:, H:].contiguous()
silu_up = (F.silu(gate.float()) * up.float()).to(fp16).contiguous()
torch.cuda.synchronize()
amax_list.append(float(silu_up.float().abs().max().item()))
dn = torch.empty(Se, D, dtype=fp16, device="cuda")
gemm.fp16_nn(silu_up.data_ptr(), w_dn[i].data_ptr(), dn.data_ptr(),
Se, D, H, stream)
fvk.residual_add_fp16(x.data_ptr(), dn.data_ptr(), Se * D, stream)
return amax_list
def _calibrate_qwen3_impl(sd, gemm, fvk, qwen3, ie_fp16, stream=0):
"""FP16 shadow forward through Qwen3, returns 3*L FP8 activation scales.
Thin wrapper preserved for backward compatibility with the legacy
single-sample calibration path. Bit-equal to the pre-refactor
implementation.
"""
return [_cal_scale(a) for a in _calibrate_qwen3_collect_amax(
sd, gemm, fvk, qwen3, ie_fp16, stream)]
def _calibrate_qwen3_per_sample(sd, gemm, fvk, qwen3, ie_fp16_list, stream=0):
"""Run Qwen3 amax collection N times.
Returns an ``[N, 3*L]`` float32 numpy array of raw amax values, ready
for ``flash_rt.core.calibration.accumulate_amax`` percentile reduction.
"""
if not ie_fp16_list:
raise ValueError("ie_fp16_list must be non-empty")
rows = [_calibrate_qwen3_collect_amax(sd, gemm, fvk, qwen3, ie, stream)
for ie in ie_fp16_list]
return np.asarray(rows, dtype=np.float32)
def _calibrate_dit_collect_amax(sd, gemm, fvk, dit, cal_tensors, state_feat,
actions_fp32, stream=0):
"""FP16 shadow forward through DiT (step=0), returns 3*L raw amax.
Stateless: each call processes one sample and returns its raw amax
list. Cross-attention layers (``l % 2 == 0``) have no learnable
pre-attention scale; their first slot is filled with ``float('nan')``
as a sentinel so multi-sample reducers can preserve the constant
placeholder ``1.0 / _FP8_MAX`` that the FP8 path expects.
"""
Se = dit.Se
T = dit.T
Sa = dit.Sa
D, H, NH, HD, L = DIT_D, DIT_H, DIT_NH, DIT_HD, DIT_L
prefix = f"{DIT_PREFIX}.transformer_blocks"
ada_scales = cal_tensors["ada_scales"]
ada_shifts = cal_tensors["ada_shifts"]
ate = cal_tensors["ate"]
pos_emb = cal_tensors["pos_emb"]
ae_w1, ae_b1 = cal_tensors["action_enc_w1"], cal_tensors["action_enc_b1"]
ae_w2, ae_b2 = cal_tensors["action_enc_w2"], cal_tensors["action_enc_b2"]
ae_w3, ae_b3 = cal_tensors["action_enc_w3"], cal_tensors["action_enc_b3"]
w_qkv_self, w_qkv_self_b = [None] * L, [None] * L
w_q, w_q_b = [None] * L, [None] * L
w_o, w_o_b = [None] * L, [None] * L
w_ff_up, w_ff_up_b = [None] * L, [None] * L
w_ff_dn, w_ff_dn_b = [None] * L, [None] * L
for l in range(L):
lp = f"{prefix}.{l}"
q_w = sd[f"{lp}.attn1.to_q.weight"]
k_w = sd[f"{lp}.attn1.to_k.weight"]
v_w = sd[f"{lp}.attn1.to_v.weight"]
o_w = sd[f"{lp}.attn1.to_out.0.weight"]
q_b = sd[f"{lp}.attn1.to_q.bias"].to(fp16).contiguous()
k_b = sd[f"{lp}.attn1.to_k.bias"].to(fp16).contiguous()
v_b = sd[f"{lp}.attn1.to_v.bias"].to(fp16).contiguous()
o_b = sd[f"{lp}.attn1.to_out.0.bias"].to(fp16).contiguous()
w_q[l] = q_w.T.contiguous().to(fp16)
w_q_b[l] = q_b
w_o[l] = o_w.T.contiguous().to(fp16)
w_o_b[l] = o_b
if l % 2 == 1:
qkv_m = torch.cat([q_w, k_w, v_w], dim=0).T.contiguous().to(fp16)
qkv_b = torch.cat([q_b, k_b, v_b]).to(fp16).contiguous()
w_qkv_self[l] = qkv_m
w_qkv_self_b[l] = qkv_b
up_w = sd[f"{lp}.ff.net.0.proj.weight"].T.contiguous().to(fp16)
up_b = sd[f"{lp}.ff.net.0.proj.bias"].to(fp16).contiguous()
dn_w = sd[f"{lp}.ff.net.2.weight"].T.contiguous().to(fp16)
dn_b = sd[f"{lp}.ff.net.2.bias"].to(fp16).contiguous()
w_ff_up[l], w_ff_up_b[l] = up_w, up_b
w_ff_dn[l], w_ff_dn_b[l] = dn_w, dn_b
actions_fp16 = actions_fp32[:T].to(fp16).contiguous()
a_emb = torch.empty(T, D, dtype=fp16, device="cuda")
gemm.fp16_nn(actions_fp16.data_ptr(), ae_w1.data_ptr(), a_emb.data_ptr(),
T, D, actions_fp16.shape[-1], stream)
fvk.add_bias_fp16(a_emb.data_ptr(), ae_b1.data_ptr(), T, D, stream)
concat = torch.empty(T, 2 * D, dtype=fp16, device="cuda")
fvk.gpu_copy(concat.data_ptr(), a_emb.data_ptr(), T * D * 2, stream)
fvk.gpu_copy(concat.data_ptr() + T * D * 2, ate[0].data_ptr(), T * D * 2, stream)
enc_h = torch.empty(T, D, dtype=fp16, device="cuda")
gemm.fp16_nn(concat.data_ptr(), ae_w2.data_ptr(), enc_h.data_ptr(),
T, D, 2 * D, stream)
fvk.add_bias_fp16(enc_h.data_ptr(), ae_b2.data_ptr(), T, D, stream)
fvk.silu_inplace_fp16(enc_h.data_ptr(), T * D, stream)
gemm.fp16_nn(enc_h.data_ptr(), ae_w3.data_ptr(), a_emb.data_ptr(),
T, D, D, stream)
fvk.add_bias_fp16(a_emb.data_ptr(), ae_b3.data_ptr(), T, D, stream)
fvk.residual_add_fp16(a_emb.data_ptr(), pos_emb.data_ptr(), T * D, stream)
hidden = torch.empty(Sa, D, dtype=fp16, device="cuda")
fvk.gpu_copy(hidden.data_ptr(), state_feat.data_ptr(), D * 2, stream)
fvk.gpu_copy(hidden.data_ptr() + D * 2, a_emb.data_ptr(), T * D * 2, stream)
torch.cuda.synchronize()
h_norm = torch.empty(Sa, D, dtype=fp16, device="cuda")
amax_list = []
for l in range(L):
is_self = (l % 2 == 1)
fvk.ada_layer_norm_fp16(
hidden.data_ptr(),
ada_scales[0, l].data_ptr(), ada_shifts[0, l].data_ptr(),
h_norm.data_ptr(), Sa, D, 1e-5, stream)
torch.cuda.synchronize()
if is_self:
amax_list.append(float(h_norm[:Sa].float().abs().max().item()))
else:
amax_list.append(float('nan'))
if is_self:
qkv = torch.empty(Sa, 3 * D, dtype=fp16, device="cuda")
gemm.fp16_nn(h_norm.data_ptr(), w_qkv_self[l].data_ptr(),
qkv.data_ptr(), Sa, 3 * D, D, stream)
fvk.add_bias_fp16(qkv.data_ptr(), w_qkv_self_b[l].data_ptr(),
Sa, 3 * D, stream)
Q = qkv[:, :D].contiguous().view(Sa, NH, HD)
K = qkv[:, D:2 * D].contiguous().view(Sa, NH, HD)
V = qkv[:, 2 * D:].contiguous().view(Sa, NH, HD)
q_s = Q.unsqueeze(0).transpose(1, 2)
k_s = K.unsqueeze(0).transpose(1, 2)
v_s = V.unsqueeze(0).transpose(1, 2)
attn = F.scaled_dot_product_attention(q_s, k_s, v_s)
attn_flat = attn.transpose(1, 2).reshape(Sa, D).to(fp16).contiguous()
else:
Q = torch.empty(Sa, D, dtype=fp16, device="cuda")
gemm.fp16_nn(h_norm.data_ptr(), w_q[l].data_ptr(), Q.data_ptr(),
Sa, D, D, stream)
fvk.add_bias_fp16(Q.data_ptr(), w_q_b[l].data_ptr(), Sa, D, stream)
cross_idx = l // 2
K_pre = dit.attn.dit_cross_K[cross_idx][:Se]
V_pre = dit.attn.dit_cross_V[cross_idx][:Se]
q_s = Q.view(Sa, NH, HD).unsqueeze(0).transpose(1, 2)
k_s = K_pre.unsqueeze(0).transpose(1, 2)
v_s = V_pre.unsqueeze(0).transpose(1, 2)
attn = F.scaled_dot_product_attention(q_s, k_s, v_s)
attn_flat = attn.transpose(1, 2).reshape(Sa, D).to(fp16).contiguous()
o_out = torch.empty(Sa, D, dtype=fp16, device="cuda")
gemm.fp16_nn(attn_flat.data_ptr(), w_o[l].data_ptr(), o_out.data_ptr(),
Sa, D, D, stream)
fvk.add_bias_fp16(o_out.data_ptr(), w_o_b[l].data_ptr(), Sa, D, stream)
fvk.residual_add_fp16(hidden.data_ptr(), o_out.data_ptr(), Sa * D, stream)
fvk.layer_norm_no_affine_fp16(hidden.data_ptr(), h_norm.data_ptr(),
Sa, D, 1e-5, stream)
torch.cuda.synchronize()
amax_list.append(float(h_norm[:Sa].float().abs().max().item()))
ff_h = torch.empty(Sa, H, dtype=fp16, device="cuda")
gemm.fp16_nn(h_norm.data_ptr(), w_ff_up[l].data_ptr(), ff_h.data_ptr(),
Sa, H, D, stream)
fvk.add_bias_fp16(ff_h.data_ptr(), w_ff_up_b[l].data_ptr(), Sa, H, stream)
fvk.gelu_inplace_fp16(ff_h.data_ptr(), Sa * H, stream)
torch.cuda.synchronize()
amax_list.append(float(ff_h[:Sa].float().abs().max().item()))
ff_out = torch.empty(Sa, D, dtype=fp16, device="cuda")
gemm.fp16_nn(ff_h.data_ptr(), w_ff_dn[l].data_ptr(), ff_out.data_ptr(),
Sa, D, H, stream)
fvk.add_bias_fp16(ff_out.data_ptr(), w_ff_dn_b[l].data_ptr(), Sa, D, stream)
fvk.residual_add_fp16(hidden.data_ptr(), ff_out.data_ptr(), Sa * D, stream)
return amax_list
def _calibrate_dit_impl(sd, gemm, fvk, dit, cal_tensors, state_feat,
actions_fp32, stream=0):
"""FP16 shadow forward through DiT (step=0), returns 3*L FP8 activation scales.
Thin wrapper preserved for backward compatibility with the legacy
single-sample calibration path. ``NaN`` slots emitted by the
collector for cross-attention layers are mapped to the constant
``1.0 / _FP8_MAX`` placeholder, matching the pre-refactor behavior.
"""
raw = _calibrate_dit_collect_amax(
sd, gemm, fvk, dit, cal_tensors, state_feat, actions_fp32, stream)
return [(1.0 / _FP8_MAX) if math.isnan(a) else _cal_scale(a) for a in raw]
def _calibrate_dit_per_sample(sd, gemm, fvk, dit, cal_tensors_list,
state_feat_list, actions_fp32_list, stream=0):
"""Run DiT amax collection for N samples.
Returns an ``[N, 3*L]`` float32 numpy array of raw amax values. Cross
layers contribute ``NaN`` at their first slot in every row; downstream
reducers must treat all-NaN columns as placeholders rather than
propagating NaN into the final FP8 scale.
All three list arguments (``cal_tensors_list``, ``state_feat_list``,
``actions_fp32_list``) must have the same length, one entry per
calibration sample.
"""
n = len(cal_tensors_list)
if n == 0:
raise ValueError("cal_tensors_list must be non-empty")
if len(state_feat_list) != n or len(actions_fp32_list) != n:
raise ValueError(
f"length mismatch: cal_tensors={n}, "
f"state_feat={len(state_feat_list)}, "
f"actions_fp32={len(actions_fp32_list)}")
rows = [_calibrate_dit_collect_amax(
sd, gemm, fvk, dit, cal_tensors_list[i],
state_feat_list[i], actions_fp32_list[i], stream)
for i in range(n)]
return np.asarray(rows, dtype=np.float32)
# ════════════════════════════════════════════════════════════════════
# GrootTorchFrontendRtx frontend
# ════════════════════════════════════════════════════════════════════
class GrootTorchFrontendRtx:
"""RTX consumer GPU GROOT N1.6 torch frontend.
Mirrors the :class:`ThorPipelineTorchGroot` public API
(``set_prompt`` + ``infer``) so the same eval scripts work on both
hardware families.
"""
def __init__(
self,
checkpoint_dir: Union[str, pathlib.Path],
num_views: int = 2,
embodiment_tag: str = "new_embodiment",
action_horizon: int = ACTION_HORIZON_MAX,
use_fp8: bool = True,
):
if not (1 <= int(action_horizon) <= ACTION_HORIZON_MAX):
raise ValueError(
f"action_horizon must be in [1, {ACTION_HORIZON_MAX}], "
f"got {action_horizon}")
if embodiment_tag not in EMBODIMENT_TAG_TO_INDEX:
raise ValueError(
f"Unknown embodiment_tag {embodiment_tag!r}. "
f"Known tags: {sorted(EMBODIMENT_TAG_TO_INDEX.keys())}. "
f"Trained in GR00T-N1.6-3B: {PUBLIC_TRAINED_TAGS}.")
self._checkpoint_dir = pathlib.Path(checkpoint_dir)
self._num_views = int(num_views)
self.use_fp8 = bool(use_fp8)
self._embodiment_tag = embodiment_tag
self._embodiment_id = EMBODIMENT_TAG_TO_INDEX[embodiment_tag]
self._calibrated = False
if not is_embodiment_trained(embodiment_tag):
logger.warning(
"embodiment_tag=%r (id=%d) is NOT trained in the GR00T-N1.6-3B "
"base checkpoint — per-embodiment MLP weights are at "
"initialization and the model will emit noise-like actions. "
"Pick one of %s for a demo, or fine-tune this slot before "
"deployment.",
embodiment_tag, self._embodiment_id, PUBLIC_TRAINED_TAGS,
)
self.latency_records: list[float] = []
self._graphs_built = False
# ── Init kernels ──
from flash_rt import flash_rt_kernels as fvk
self._fvk = fvk
self._gemm = fvk.GemmRunner()
self._cudart = ctypes.CDLL("libcudart.so")
# ── Load checkpoint into memory ──
self._load_checkpoint()
# ── Action / state dims (padded max — actual depends on embodiment) ──
self._action_horizon = int(action_horizon)
logger.info(
"GrootTorchFrontendRtx initialised (num_views=%d, embodiment=%s id=%d)",
self._num_views, embodiment_tag, self._embodiment_id,
)
# ─────────────────────────────────────────────────────────────
# Checkpoint loading
# ─────────────────────────────────────────────────────────────
def _load_checkpoint(self) -> None:
"""Load all safetensors files into a state dict on GPU."""
from safetensors import safe_open
st_files = sorted(self._checkpoint_dir.glob("*.safetensors"))
if not st_files:
raise FileNotFoundError(
f"No safetensors found in {self._checkpoint_dir}")
logger.info("Loading %d safetensors files...", len(st_files))
sd = {}
for f in st_files:
with safe_open(str(f), framework="pt", device="cuda") as sf:
for k in sf.keys():
sd[k] = sf.get_tensor(k)
logger.info("Loaded %d tensors", len(sd))
self._sd = sd
# Extract token embeddings (needed for set_prompt)
self._qwen3_embed = sd[f"{LLM_PREFIX}.embed_tokens.weight"]
# ─────────────────────────────────────────────────────────────
# SigLIP2 weight loading
# ─────────────────────────────────────────────────────────────
def _build_siglip_weights(self) -> dict:
"""Build the weights dict for GrootSigLIP2 from the loaded sd.
FP8-quantizes QKV / O / FFN-up / FFN-down per layer; keeps norms
and biases as fp16. Stores all tensors on the frontend (not
deleted) so the data_ptr() values stay valid for the captured
graph.
"""
sd = self._sd
store = self._weight_store
logger.info("Building SigLIP2 weights (FP8 quantize)...")
prefix = f"{VIS_PREFIX}.encoder.layers"
ln_attn_w_list, ln_attn_b_list = [], []
ln_ffn_w_list, ln_ffn_b_list = [], []
qkv_b_list, o_b_list, up_b_list, down_b_list = [], [], [], []
fp8_weights = {}
def _stash(t):
store.append(t)
return t
for i in range(VIS_L):
lp = f"{prefix}.{i}"
ln_attn_w_list.append(_stash(sd[f"{lp}.layer_norm1.weight"].to(fp16).contiguous()))
ln_attn_b_list.append(_stash(sd[f"{lp}.layer_norm1.bias"].to(fp16).contiguous()))
ln_ffn_w_list.append(_stash(sd[f"{lp}.layer_norm2.weight"].to(fp16).contiguous()))
ln_ffn_b_list.append(_stash(sd[f"{lp}.layer_norm2.bias"].to(fp16).contiguous()))
# QKV (cat then transpose) → FP8
qkv_cat = torch.cat(
[sd[f"{lp}.self_attn.{p}_proj.weight"] for p in ("q", "k", "v")],
dim=0,
) # (3D, D)
qkv_T = qkv_cat.T.contiguous() # (D, 3D)
qkv_fp8, qs = _quant_fp8(qkv_T)
qkv_scale = torch.tensor([qs], dtype=torch.float32, device="cuda")
_stash(qkv_fp8); _stash(qkv_scale)
fp8_weights[f"vision_attn_qkv_w_{i}"] = (qkv_fp8.data_ptr(), qkv_scale.data_ptr())
qkv_b_list.append(_stash(torch.cat(
[sd[f"{lp}.self_attn.{p}_proj.bias"] for p in ("q", "k", "v")]).to(fp16).contiguous()))
# O proj → FP8
o_T = sd[f"{lp}.self_attn.out_proj.weight"].T.contiguous()
o_fp8, os_ = _quant_fp8(o_T)
o_scale = torch.tensor([os_], dtype=torch.float32, device="cuda")
_stash(o_fp8); _stash(o_scale)
fp8_weights[f"vision_attn_o_w_{i}"] = (o_fp8.data_ptr(), o_scale.data_ptr())
o_b_list.append(_stash(sd[f"{lp}.self_attn.out_proj.bias"].to(fp16).contiguous()))
# FFN up → FP8
up_T = sd[f"{lp}.mlp.fc1.weight"].T.contiguous()
up_fp8, us = _quant_fp8(up_T)
up_scale = torch.tensor([us], dtype=torch.float32, device="cuda")
_stash(up_fp8); _stash(up_scale)
fp8_weights[f"vision_ffn_up_w_{i}"] = (up_fp8.data_ptr(), up_scale.data_ptr())
up_b_list.append(_stash(sd[f"{lp}.mlp.fc1.bias"].to(fp16).contiguous()))
# FFN down → FP8
dn_T = sd[f"{lp}.mlp.fc2.weight"].T.contiguous()
dn_fp8, ds = _quant_fp8(dn_T)
dn_scale = torch.tensor([ds], dtype=torch.float32, device="cuda")
_stash(dn_fp8); _stash(dn_scale)
fp8_weights[f"vision_ffn_down_w_{i}"] = (dn_fp8.data_ptr(), dn_scale.data_ptr())
down_b_list.append(_stash(sd[f"{lp}.mlp.fc2.bias"].to(fp16).contiguous()))
# Stack per-layer lists into (L, ...) tensors so we can pass per-layer
# data_ptr() via tensor.data_ptr() + i * stride. Or simpler: keep as
# Python list of int ptrs.
ln_attn_w_ptrs = [w.data_ptr() for w in ln_attn_w_list]
ln_attn_b_ptrs = [w.data_ptr() for w in ln_attn_b_list]
ln_ffn_w_ptrs = [w.data_ptr() for w in ln_ffn_w_list]
ln_ffn_b_ptrs = [w.data_ptr() for w in ln_ffn_b_list]
qkv_b_ptrs = [w.data_ptr() for w in qkv_b_list]
o_b_ptrs = [w.data_ptr() for w in o_b_list]
up_b_ptrs = [w.data_ptr() for w in up_b_list]
down_b_ptrs = [w.data_ptr() for w in down_b_list]
# Patch embedding (Linear, NOT Conv2d): HF stores (1152, 588) =
# (out, in). For our row-major NN GEMM we want (in=588, out=1152) → .T
pe_w = _stash(sd[f"{VIS_PREFIX}.embeddings.patch_embedding.weight"]
.T.contiguous().to(fp16)) # (588, 1152)
pe_b = _stash(sd[f"{VIS_PREFIX}.embeddings.patch_embedding.bias"]
.to(fp16).contiguous()) # (1152,)
pos_emb = _stash(sd[f"{VIS_PREFIX}.embeddings.position_embedding.weight"]
.to(fp16).contiguous()) # (256, 1152)
# Post-LayerNorm
post_ln_w = _stash(sd[f"{VIS_PREFIX}.post_layernorm.weight"].to(fp16).contiguous())
post_ln_b = _stash(sd[f"{VIS_PREFIX}.post_layernorm.bias"].to(fp16).contiguous())
# mlp1: LN(4608) → Linear(4608→2048) → GELU → Linear(2048→2048)
mlp1_ln_w = _stash(sd[f"{MLP1_PREFIX}.0.weight"].to(fp16).contiguous())
mlp1_ln_b = _stash(sd[f"{MLP1_PREFIX}.0.bias"].to(fp16).contiguous())
mlp1_fc1_w = _stash(sd[f"{MLP1_PREFIX}.1.weight"].T.contiguous().to(fp16))
mlp1_fc1_b = _stash(sd[f"{MLP1_PREFIX}.1.bias"].to(fp16).contiguous())
mlp1_fc2_w = _stash(sd[f"{MLP1_PREFIX}.3.weight"].T.contiguous().to(fp16))
mlp1_fc2_b = _stash(sd[f"{MLP1_PREFIX}.3.bias"].to(fp16).contiguous())
return {
"vision_patch_embedding_w": pe_w.data_ptr(),
"vision_patch_embedding_b": pe_b.data_ptr(),
"vision_position_embedding": pos_emb.data_ptr(),
"vision_pre_attn_norm_w": ln_attn_w_ptrs,
"vision_pre_attn_norm_b": ln_attn_b_ptrs,
"vision_pre_ffn_norm_w": ln_ffn_w_ptrs,
"vision_pre_ffn_norm_b": ln_ffn_b_ptrs,
"vision_attn_qkv_b": qkv_b_ptrs,
"vision_attn_o_b": o_b_ptrs,
"vision_ffn_up_b": up_b_ptrs,
"vision_ffn_down_b": down_b_ptrs,
"vision_post_norm_w": post_ln_w.data_ptr(),
"vision_post_norm_b": post_ln_b.data_ptr(),
"mlp1_ln_w": mlp1_ln_w.data_ptr(),
"mlp1_ln_b": mlp1_ln_b.data_ptr(),
"mlp1_fc1_w": mlp1_fc1_w.data_ptr(),
"mlp1_fc1_b": mlp1_fc1_b.data_ptr(),
"mlp1_fc2_w": mlp1_fc2_w.data_ptr(),
"mlp1_fc2_b": mlp1_fc2_b.data_ptr(),
"fp8": fp8_weights,
}
# ─────────────────────────────────────────────────────────────
# Qwen3 weight loading
# ─────────────────────────────────────────────────────────────
def _build_qwen3_weights(self) -> dict:
sd = self._sd
store = self._weight_store
logger.info("Building Qwen3 weights (16 layers, FP8 quantize)...")
prefix = f"{LLM_PREFIX}.layers"
ln_attn_w_ptrs, ln_ffn_w_ptrs = [], []
q_norm_w_ptrs, k_norm_w_ptrs = [], []
o_w_ptrs = []
fp8_weights = {}
def _stash(t):
store.append(t)
return t
for i in range(QWEN3_L):
lp = f"{prefix}.{i}"
ln_attn_w_ptrs.append(_stash(sd[f"{lp}.input_layernorm.weight"].to(fp16).contiguous()).data_ptr())
ln_ffn_w_ptrs.append(_stash(sd[f"{lp}.post_attention_layernorm.weight"].to(fp16).contiguous()).data_ptr())
q_norm_w_ptrs.append(_stash(sd[f"{lp}.self_attn.q_norm.weight"].to(fp16).contiguous()).data_ptr())
k_norm_w_ptrs.append(_stash(sd[f"{lp}.self_attn.k_norm.weight"].to(fp16).contiguous()).data_ptr())
# QKV merged: HF stores per-proj (out, in); cat then .T → (D, QKV_DIM)
q_w = sd[f"{lp}.self_attn.q_proj.weight"]
k_w = sd[f"{lp}.self_attn.k_proj.weight"]
v_w = sd[f"{lp}.self_attn.v_proj.weight"]
qkv_T = torch.cat([q_w, k_w, v_w], dim=0).T.contiguous()
qkv_fp8, qs = _quant_fp8(qkv_T)
qkv_scale = torch.tensor([qs], dtype=torch.float32, device="cuda")
_stash(qkv_fp8); _stash(qkv_scale)
fp8_weights[f"qwen3_qkv_w_{i}"] = (qkv_fp8.data_ptr(), qkv_scale.data_ptr())
# O proj fp16 (small M)
o_w = sd[f"{lp}.self_attn.o_proj.weight"].T.contiguous().to(fp16)
_stash(o_w)
o_w_ptrs.append(o_w.data_ptr())
# Gate+Up merged
g_w = sd[f"{lp}.mlp.gate_proj.weight"]
u_w = sd[f"{lp}.mlp.up_proj.weight"]
gu_T = torch.cat([g_w, u_w], dim=0).T.contiguous()
gu_fp8, gs = _quant_fp8(gu_T)
gu_scale = torch.tensor([gs], dtype=torch.float32, device="cuda")
_stash(gu_fp8); _stash(gu_scale)
fp8_weights[f"qwen3_gate_up_w_{i}"] = (gu_fp8.data_ptr(), gu_scale.data_ptr())
# Down
dn_T = sd[f"{lp}.mlp.down_proj.weight"].T.contiguous()
dn_fp8, ds = _quant_fp8(dn_T)
dn_scale = torch.tensor([ds], dtype=torch.float32, device="cuda")
_stash(dn_fp8); _stash(dn_scale)
fp8_weights[f"qwen3_down_w_{i}"] = (dn_fp8.data_ptr(), dn_scale.data_ptr())
final_norm_w = _stash(sd[f"{LLM_PREFIX}.norm.weight"].to(fp16).contiguous())
vlln_w = _stash(sd[f"{AH_PREFIX}.vlln.weight"].to(fp16).contiguous())
vlln_b = _stash(sd[f"{AH_PREFIX}.vlln.bias"].to(fp16).contiguous())
return {
"qwen3_ln_attn_w": ln_attn_w_ptrs,
"qwen3_ln_ffn_w": ln_ffn_w_ptrs,
"qwen3_q_norm_w": q_norm_w_ptrs,
"qwen3_k_norm_w": k_norm_w_ptrs,
"qwen3_o_w_fp16": o_w_ptrs,
"qwen3_final_norm_w": final_norm_w.data_ptr(),
"vlln_w": vlln_w.data_ptr(),
"vlln_b": vlln_b.data_ptr(),
"fp8": fp8_weights,
}
# ─────────────────────────────────────────────────────────────
# DiT weight loading
# ─────────────────────────────────────────────────────────────
def _build_dit_weights(self) -> dict:
sd = self._sd
store = self._weight_store
logger.info("Building DiT weights (32 blocks)...")
prefix = f"{DIT_PREFIX}.transformer_blocks"
q_w_fp16_ptrs, q_b_ptrs = [], []
k_w_fp16_ptrs, k_b_ptrs = [], []
v_w_fp16_ptrs, v_b_ptrs = [], []
o_w_fp16_ptrs, o_b_ptrs = [], []
ff_up_b_ptrs, ff_down_b_ptrs = [], []
qkv_b_self_ptrs = []
fp8_weights = {}
def _stash(t):
store.append(t)
return t
# Per-step / per-layer norm1.linear (used during _precompute_conditioning)
norm1_lin_w_list = []
norm1_lin_b_list = []
for l in range(DIT_L):
is_self = (l % 2 == 1)
lp = f"{prefix}.{l}"
# Q/K/V/O fp16 weights
q_w_T = sd[f"{lp}.attn1.to_q.weight"].T.contiguous().to(fp16)
k_w_T = sd[f"{lp}.attn1.to_k.weight"].T.contiguous().to(fp16)
v_w_T = sd[f"{lp}.attn1.to_v.weight"].T.contiguous().to(fp16)
o_w_T = sd[f"{lp}.attn1.to_out.0.weight"].T.contiguous().to(fp16)
q_b = sd[f"{lp}.attn1.to_q.bias"].to(fp16).contiguous()
k_b = sd[f"{lp}.attn1.to_k.bias"].to(fp16).contiguous()
v_b = sd[f"{lp}.attn1.to_v.bias"].to(fp16).contiguous()
o_b = sd[f"{lp}.attn1.to_out.0.bias"].to(fp16).contiguous()
for t in (q_w_T, k_w_T, v_w_T, o_w_T, q_b, k_b, v_b, o_b):
_stash(t)
q_w_fp16_ptrs.append(q_w_T.data_ptr())
k_w_fp16_ptrs.append(k_w_T.data_ptr())
v_w_fp16_ptrs.append(v_w_T.data_ptr())
o_w_fp16_ptrs.append(o_w_T.data_ptr())
q_b_ptrs.append(q_b.data_ptr())
k_b_ptrs.append(k_b.data_ptr())
v_b_ptrs.append(v_b.data_ptr())
o_b_ptrs.append(o_b.data_ptr())
# Self-attn merged QKV (only at odd layers)
if is_self:
qkv_m = torch.cat([
sd[f"{lp}.attn1.to_q.weight"],
sd[f"{lp}.attn1.to_k.weight"],
sd[f"{lp}.attn1.to_v.weight"],
], dim=0).T.contiguous()
qkv_fp8, qs = _quant_fp8(qkv_m)
qkv_scale = torch.tensor([qs], dtype=torch.float32, device="cuda")
_stash(qkv_fp8); _stash(qkv_scale)
fp8_weights[f"dit_qkv_w_{l}"] = (qkv_fp8.data_ptr(), qkv_scale.data_ptr())
qkv_b = torch.cat([q_b, k_b, v_b]).to(fp16).contiguous()
_stash(qkv_b)
qkv_b_self_ptrs.append(qkv_b.data_ptr())
else:
# Dummy entry; the pipeline only reads at odd indices
qkv_b_self_ptrs.append(0)
# FFN up + down → FP8
up_T = sd[f"{lp}.ff.net.0.proj.weight"].T.contiguous()
dn_T = sd[f"{lp}.ff.net.2.weight"].T.contiguous()
up_fp8, us = _quant_fp8(up_T)
dn_fp8, ds = _quant_fp8(dn_T)
up_scale = torch.tensor([us], dtype=torch.float32, device="cuda")
dn_scale = torch.tensor([ds], dtype=torch.float32, device="cuda")
_stash(up_fp8); _stash(dn_fp8); _stash(up_scale); _stash(dn_scale)
fp8_weights[f"dit_ff_up_w_{l}"] = (up_fp8.data_ptr(), up_scale.data_ptr())
fp8_weights[f"dit_ff_down_w_{l}"] = (dn_fp8.data_ptr(), dn_scale.data_ptr())
ff_up_b = sd[f"{lp}.ff.net.0.proj.bias"].to(fp16).contiguous()
ff_dn_b = sd[f"{lp}.ff.net.2.bias"].to(fp16).contiguous()
_stash(ff_up_b); _stash(ff_dn_b)
ff_up_b_ptrs.append(ff_up_b.data_ptr())
ff_down_b_ptrs.append(ff_dn_b.data_ptr())
# norm1.linear (for conditioning precompute, not used inside the
# captured graph — the pipeline reads pre-baked ada_scales/shifts)
norm1_lin_w = sd[f"{lp}.norm1.linear.weight"].T.contiguous().to(fp16)
norm1_lin_b = sd[f"{lp}.norm1.linear.bias"].to(fp16).contiguous()
_stash(norm1_lin_w); _stash(norm1_lin_b)
norm1_lin_w_list.append(norm1_lin_w)
norm1_lin_b_list.append(norm1_lin_b)
# Output projection
proj_out_1_w = _stash(sd[f"{DIT_PREFIX}.proj_out_1.weight"].T.contiguous().to(fp16))
proj_out_1_b = _stash(sd[f"{DIT_PREFIX}.proj_out_1.bias"].to(fp16).contiguous())
proj_out_2_w = _stash(sd[f"{DIT_PREFIX}.proj_out_2.weight"].T.contiguous().to(fp16))
proj_out_2_b = _stash(sd[f"{DIT_PREFIX}.proj_out_2.bias"].to(fp16).contiguous())
# Timestep encoder weights (used during conditioning precompute)
ts_pre = f"{DIT_PREFIX}.timestep_encoder.timestep_embedder"
ts_l1_w = sd[f"{ts_pre}.linear_1.weight"].T.contiguous().to(fp16)
ts_l1_b = sd[f"{ts_pre}.linear_1.bias"].to(fp16)
ts_l2_w = sd[f"{ts_pre}.linear_2.weight"].T.contiguous().to(fp16)
ts_l2_b = sd[f"{ts_pre}.linear_2.bias"].to(fp16)
# ── Per-step + per-layer pre-computed conditioning ──
ada_scales, ada_shifts, out_scales, out_shifts, ate = \
self._precompute_conditioning(
ts_l1_w, ts_l1_b, ts_l2_w, ts_l2_b,
norm1_lin_w_list, norm1_lin_b_list,
proj_out_1_w, proj_out_1_b,
)
for t in (ada_scales, ada_shifts, out_scales, out_shifts, ate):
_stash(t)
# ── Per-embodiment MLPs ──
eid = self._embodiment_id
def _emb(name):
t = sd[f"{AH_PREFIX}.{name}"][eid].contiguous().to(fp16)
_stash(t)
return t
def _emb_b(name):
t = sd[f"{AH_PREFIX}.{name}"][eid].to(fp16).contiguous()
_stash(t)
return t
state_enc_w1 = _emb("state_encoder.layer1.W")
state_enc_b1 = _emb_b("state_encoder.layer1.b")
state_enc_w2 = _emb("state_encoder.layer2.W")
state_enc_b2 = _emb_b("state_encoder.layer2.b")
action_enc_w1 = _emb("action_encoder.W1.W")
action_enc_b1 = _emb_b("action_encoder.W1.b")
action_enc_w2 = _emb("action_encoder.W2.W")
action_enc_b2 = _emb_b("action_encoder.W2.b")
action_enc_w3 = _emb("action_encoder.W3.W")
action_enc_b3 = _emb_b("action_encoder.W3.b")
action_dec_w1 = _emb("action_decoder.layer1.W")
action_dec_b1 = _emb_b("action_decoder.layer1.b")
action_dec_w2 = _emb("action_decoder.layer2.W")
action_dec_b2 = _emb_b("action_decoder.layer2.b")
pos_emb = _stash(sd[f"{AH_PREFIX}.position_embedding.weight"].to(fp16).contiguous())
# Save state encoder for runtime use
self._state_enc_w1 = state_enc_w1
self._state_enc_b1 = state_enc_b1
self._state_enc_w2 = state_enc_w2
self._state_enc_b2 = state_enc_b2
# Keep torch tensors alive for the FP8 calibration pass (groot_calibration
# needs the raw tensors, not just device pointers, to run a shadow forward).
self._cal_dit_tensors = {
"ada_scales": ada_scales,
"ada_shifts": ada_shifts,
"ate": ate,
"pos_emb": pos_emb,
"action_enc_w1": action_enc_w1,
"action_enc_b1": action_enc_b1,
"action_enc_w2": action_enc_w2,
"action_enc_b2": action_enc_b2,
"action_enc_w3": action_enc_w3,
"action_enc_b3": action_enc_b3,
}
return {
"dit_q_w_fp16": q_w_fp16_ptrs,
"dit_q_b": q_b_ptrs,
"dit_k_w_fp16": k_w_fp16_ptrs,
"dit_k_b": k_b_ptrs,
"dit_v_w_fp16": v_w_fp16_ptrs,
"dit_v_b": v_b_ptrs,
"dit_o_w_fp16": o_w_fp16_ptrs,
"dit_o_b": o_b_ptrs,
"dit_qkv_b_self": qkv_b_self_ptrs,
"dit_ff_up_b": ff_up_b_ptrs,
"dit_ff_down_b": ff_down_b_ptrs,
"ada_scales": ada_scales.data_ptr(),
"ada_shifts": ada_shifts.data_ptr(),
"out_scales": out_scales.data_ptr(),
"out_shifts": out_shifts.data_ptr(),
"action_time_embeds": ate.data_ptr(),
"action_enc_w1": action_enc_w1.data_ptr(),
"action_enc_b1": action_enc_b1.data_ptr(),
"action_enc_w2": action_enc_w2.data_ptr(),
"action_enc_b2": action_enc_b2.data_ptr(),
"action_enc_w3": action_enc_w3.data_ptr(),
"action_enc_b3": action_enc_b3.data_ptr(),
"action_dec_w1": action_dec_w1.data_ptr(),
"action_dec_b1": action_dec_b1.data_ptr(),
"action_dec_w2": action_dec_w2.data_ptr(),
"action_dec_b2": action_dec_b2.data_ptr(),
"pos_emb": pos_emb.data_ptr(),
"proj_out_2_w": proj_out_2_w.data_ptr(),
"proj_out_2_b": proj_out_2_b.data_ptr(),
"fp8": fp8_weights,
}
def _precompute_conditioning(
self, ts_l1_w, ts_l1_b, ts_l2_w, ts_l2_b,
norm1_lin_w_list, norm1_lin_b_list,
proj_out_1_w, proj_out_1_b,
) -> tuple:
"""Pre-compute (4 steps × 32 layers) of AdaLN scale/shift,
plus per-step output conditioning, plus action time embeddings.
Returns 5 fp16 cuda tensors, each contiguously laid out so the
pipeline can index by (step * L + l) byte offset.
"""
D = DIT_D
T = self._action_horizon
steps = NUM_FLOW_STEPS
L = DIT_L