Repository navigation
Expand file tree
/
Copy pathmodel.py
More file actions
1953 lines (1747 loc) · 96.3 KB
/
Copy pathmodel.py
File metadata and controls
1953 lines (1747 loc) · 96.3 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
"""The PRISM ``UnifiedTransformer`` and its custom transformer block.
``UnifiedTransformer`` is the model: it encodes every configured modality,
projects each one into the shared backbone width, concatenates (or
interleaves) the results into one sequence, and runs that sequence through a
Hugging Face causal-LM backbone -- or, when no backbone is configured,
through the local ``TransformerBlock`` stack defined here.
Only the backbone path reaches the output decoders in ``src/decoders/``. The
no-backbone path ends at the local ``CausalLMHead`` (``self.head``, from
``src/modules/heads.py``) and an inline cross-entropy, and the structured
decoding entry points refuse it with ``NotImplementedError``.
The class docstring walks those construction stages and the two forward
paths. Everything the module builds is driven by ``ModelConfig``
(``src/config.py``).
"""
import logging
import random
from collections.abc import Mapping
import torch
import torch.nn as nn
from .config import ModelConfig
from .decoders import (
DECODERS,
GeometryDecoder,
GraphDecoder,
ImageDecoder,
LMHeadDecoder,
RegressionDecoder,
TimeSeriesDecoder,
)
from .decoders.conditioning import align_text_targets, compile_inputs
from .decoders.types import DecoderCondition, DecoderResult
from .hf_cache import load_cached_tokenizer
from .modalities import Modality
logger = logging.getLogger(__name__)
from .encoders import (
DNAEncoder,
GeometryEncoder,
GraphEncoder,
ImageEncoder,
TableEncoder,
TextEncoder,
TimeSeriesEncoder,
)
from .modules import (
CausalLMHead,
CausalSelfAttention,
ModalityProjector,
MoELayer,
PerceiverResampler,
)
from .modules.attention import RotaryEmbedding
class TransformerBlock(nn.Module):
"""One pre-norm transformer block with a sparse mixture-of-experts MLP.
The block PRISM stacks on the no-backbone path (Path B): LayerNorm ->
``CausalSelfAttention`` -> residual, then LayerNorm -> ``MoELayer`` ->
residual. The MoE layer replaces the usual dense feed-forward and returns
a load-balancing auxiliary loss alongside its output, which this block
passes straight through to its caller.
Widths, head count, expert count, dropout, maximum sequence length and
MLP flavor all come from the ``ModelConfig`` passed to ``__init__``.
"""
def __init__(self, config: ModelConfig):
super().__init__()
self.ln1 = nn.LayerNorm(config.d_model)
self.attn = CausalSelfAttention(
config.d_model, config.num_heads, config.max_seq_len, config.dropout
)
self.ln2 = nn.LayerNorm(config.d_model)
self.moe = MoELayer(
config.d_model,
config.num_experts,
config.num_experts_per_token,
config.dropout,
config.mlp_type,
)
def forward(
self, x: torch.Tensor, mask: torch.Tensor = None, freqs_cis: tuple = None
) -> tuple[torch.Tensor, torch.Tensor]:
"""Apply attention and the MoE feed-forward, each with a residual.
Args:
x: Hidden states, ``(B, T, d_model)``.
mask: Additive attention mask broadcastable to
``(B, 1, T, T)`` -- ``0.0`` to attend, a large negative value
to mask. Default: ``None``, which makes
``CausalSelfAttention`` fall back to its own causal mask.
freqs_cis: ``(cos, sin)`` rotary tables from ``RotaryEmbedding``,
applied to the queries and keys. Default: ``None`` (no RoPE).
Returns:
``(x, aux_loss)``: ``x`` is the updated hidden states, same shape
as the input; ``aux_loss`` is the scalar load-balancing loss the
block's ``MoELayer`` produced for this call, which the caller is
expected to add to the training objective.
Shape:
- x: ``(B, T, d_model)``
- output: ``(B, T, d_model)``, scalar
"""
x = x + self.attn(self.ln1(x), mask=mask, freqs_cis=freqs_cis)
moe_out, aux_loss = self.moe(self.ln2(x))
x = x + moe_out
return x, aux_loss
class UnifiedTransformer(nn.Module):
"""PRISM's multimodal model: encode every modality, fuse, decode.
One ``ModelConfig`` describes the whole network. ``__init__`` builds it in
stages, most of them marked by a ``# --- Stage N ---`` comment below:
- **Stage 0 - backbone (optional).** When ``config.llm_backbone_id`` is
set, an ``AutoModelForCausalLM`` is loaded from the local Hugging Face
cache (``local_files_only=True``) in bfloat16 on CUDA when
``torch.cuda.is_bf16_supported()``, or on any available XPU (assumed
there, not probed), and otherwise in float16. Under
``torch.distributed`` local rank 0 loads
first and the other ranks follow after a barrier, so they read a warm
cache. The tokenizer (``config.llm_tokenizer_id`` when given, else the
backbone id) lands on ``self.backbone_tokenizer`` and drives a
**grow-only** ``resize_token_embeddings``, seeded so every rank
initializes new rows identically. ``config.freeze_backbone`` then
freezes the weights, and ``self.backbone_dim`` picks up the backbone's
``hidden_size``. A failure here raises ``RuntimeError``. With no
backbone id, ``self.backbone`` stays ``None`` and ``self.backbone_dim``
remains ``config.d_model``.
- **Stage 1 - modality encoders,** plus the Stage 2 projectors that feed
on them. For each modality in ``config.modalities`` an encoder goes into
the ``self.encoders`` ``nn.ModuleDict`` and a projector to
``self.backbone_dim`` into ``self.projectors``, under the modality's
own name. Text, image and time series use ``ModalityProjector``; table,
geometry and graph use ``PerceiverResampler`` with 32 latents, giving
those modalities a fixed token budget. Text is the exception: an
external ``TextEncoder`` is built only when there is no backbone, since
otherwise the backbone's own input-embedding layer embeds the text ids.
``config.freeze_encoders`` freezes every encoder, and the frozen state
is cached in ``self._encoder_frozen_cache`` so the forward pass can skip
an O(params) check.
- **Output decoders.** ``config.output_decoders`` names what gets built
into ``self.decoders``; an unknown name raises ``ValueError``.
``self.text_decoder`` is always present, even if the config omits
``"text"``. The VLA action head is the one exception: it stays at
``self.action_head`` so existing checkpoints keep matching.
- **Stages 3 and 4 - local transformer stack,** built only when there is
no backbone: ``self.blocks`` (``config.num_layers`` instances of
``TransformerBlock``), ``self.ln_f``, rotary embeddings in
``self.rope``, and the ``CausalLMHead`` at ``self.head``.
``forward`` mirrors that split. It encodes and projects each modality
present in ``inputs``, then either interleaves the modality tokens into
the text ids at their start/end marker tokens
(``config.is_interleaved_qa``) or concatenates them as a prefix with the
text last, and runs the fused sequence through whichever stack exists --
**Path A** the HF backbone, **Path B** the local blocks. Both paths return
``(logits, loss)``. Two variants return something else: VLA mode
(``config.is_vla``) returns ``(pred_action, loss, per_dim_mse)``, and
passing ``requested_outputs`` routes to the decoder registry and returns a
``DecoderResult``. ``generate`` delegates to ``backbone.generate`` on
Path A.
Attributes:
config: The ``ModelConfig`` the model was built from.
backbone: The HF causal LM, or ``None`` on the custom path.
backbone_dim: Shared width every projector targets -- the backbone's
``hidden_size``, or ``config.d_model`` with no backbone.
encoders: ``nn.ModuleDict`` of per-modality encoders, keyed by
modality name.
projectors: ``nn.ModuleDict`` of per-modality projectors into
``backbone_dim``, keyed the same way.
decoders: ``nn.ModuleDict`` of configured output decoders.
text_decoder: The ``LMHeadDecoder`` that carries the shifted
cross-entropy on the backbone path. Always set, even with no
backbone -- but the no-backbone path never reads it.
global_step: Step counter the trainer writes onto the model.
``forward`` only reads it, to gate the ``% 100`` debug logs and
to name the step in the NaN-loss report.
"""
def __init__(self, config: ModelConfig):
super().__init__()
self.config = config
self.is_vla = config.is_vla
self._backbone_load_error = None
# --- Stage 0: Backbone (Optional) ---
self.backbone = None
self.backbone_dim = config.d_model
self.global_step = 0 # For logging purposes
if config.llm_backbone_id:
logger.info(f"Initializing HF Backbone: {config.llm_backbone_id}...")
try:
import os
import torch.distributed as dist
from transformers import AutoModelForCausalLM
# Trust remote code needed for models like Nemotron / Mamba
# Use float16 even on CPU for large models (30B+) to fit in RAM
# Prefer bfloat16 for OLMo/Llama-3 if available (MPS/Mac supports it usually)
# Enable BF16 for CUDA or XPU (Aurora)
use_bf16 = False
if torch.cuda.is_available() and torch.cuda.is_bf16_supported():
use_bf16 = True
# Check for XPU (Intel Extension for PyTorch)
elif hasattr(torch, "xpu") and torch.xpu.is_available():
use_bf16 = True
dtype = torch.bfloat16 if use_bf16 else torch.float16
# On MPS, bfloat16 is supported in recent torch, but safe fallback is float16.
# However, OLMo is trained in bf16.
# --- Fix for HuggingFace cache race condition on multi-node ---
# Only local_rank 0 on each node loads first to populate the cache,
# then other ranks load after a barrier to avoid metadata contention.
# CRITICAL: All ranks must participate in each barrier call.
local_rank = int(
os.environ.get("PALS_LOCAL_RANKID", os.environ.get("LOCAL_RANK", "0"))
)
# Load backbone with proper synchronization
backbone_loaded = False
if dist.is_initialized():
if local_rank == 0:
# Local rank 0 loads first (populates /tmp cache)
try:
self.backbone = AutoModelForCausalLM.from_pretrained(
config.llm_backbone_id,
trust_remote_code=True,
torch_dtype=dtype,
low_cpu_mem_usage=True,
local_files_only=True,
attn_implementation=config.attn_implementation,
)
logger.info(
f"Local rank 0: Backbone loaded (attn={config.attn_implementation}), "
"signaling other ranks..."
)
backbone_loaded = True
except Exception as e:
logger.error(f"Local rank 0: Error loading backbone: {e}")
self.backbone = None
# ALL ranks synchronize here - rank 0 has loaded (or failed), others are ready
dist.barrier()
# Non-zero local ranks now load from cache
if local_rank != 0:
logger.info(f"Rank {local_rank}: Loading backbone from cache...")
try:
self.backbone = AutoModelForCausalLM.from_pretrained(
config.llm_backbone_id,
trust_remote_code=True,
torch_dtype=dtype,
low_cpu_mem_usage=True,
local_files_only=True,
attn_implementation=config.attn_implementation,
)
backbone_loaded = True
except Exception as e:
logger.error(f"Rank {local_rank}: Error loading backbone: {e}")
self.backbone = None
# ALL ranks synchronize again after loading
dist.barrier()
# Load tokenizer. This ALSO drives resize_token_embeddings
# below, so it MUST match the tokenizer the data pipeline
# uses (config.llm_tokenizer_id) — not the base backbone
# tokenizer. Using the base tokenizer here shrinks the
# embedding table below the custom modality-token ids
# (e.g. <ts>=50280) that appear in every prompt, causing an
# out-of-bounds embedding gather on XPU and a delayed GPU
# write page-fault (issue #117). Mirror the single-process
# branch below, which already resolves llm_tokenizer_id.
tokenizer_id = (
config.llm_tokenizer_id
if config.llm_tokenizer_id
else config.llm_backbone_id
)
if backbone_loaded:
try:
self.backbone_tokenizer = load_cached_tokenizer(
tokenizer_id,
trust_remote_code=True,
)
except Exception as e:
logger.warning(
f"Could not load backbone tokenizer for debug logging: {e}"
)
else:
# Single process mode
self.backbone = AutoModelForCausalLM.from_pretrained(
config.llm_backbone_id,
trust_remote_code=True,
torch_dtype=dtype,
low_cpu_mem_usage=True,
local_files_only=True,
attn_implementation=config.attn_implementation,
)
backbone_loaded = True
tokenizer_id = (
config.llm_tokenizer_id
if config.llm_tokenizer_id
else config.llm_backbone_id
)
self.backbone_tokenizer = load_cached_tokenizer(
tokenizer_id,
trust_remote_code=True,
)
if self.backbone is None:
raise RuntimeError(
f"Could not load HF backbone {config.llm_backbone_id!r} "
"from the local HuggingFace cache"
)
# Grow the embedding matrix to match a custom tokenizer.
# PRISM modality tokens (<ts>, <image>, <table>, ...) push
# len(tokenizer) past the backbone's original vocab.
# Seed before resize so every rank initializes the new rows
# identically — FSDP wrap does not set sync_module_states=True
# (see training/distributed.py), so without this the new rows
# would diverge across ranks.
if backbone_loaded and hasattr(self.backbone_tokenizer, "__len__"):
# Grow-only resize. We must never shrink below the current
# embedding size: doing so drops rows that valid token ids
# index into, causing an out-of-bounds embedding gather on
# XPU and a delayed GPU write page-fault (issue #117). This
# bit us when the distributed path loaded the BASE backbone
# tokenizer (len 50280) instead of the custom interleaved
# tokenizer (len 50292) whose <ts>=50280 token appears in
# every prompt. Target = max(current, len(tokenizer)).
_before = len(self.backbone.get_input_embeddings().weight)
_target = max(_before, len(self.backbone_tokenizer))
if _target != _before:
logger.info(
f"Resizing token embeddings {_before} -> {_target} "
f"(len(tokenizer)={len(self.backbone_tokenizer)}, "
f"tokenizer_id={getattr(config, 'llm_tokenizer_id', None)!r})"
)
# Seed before resize so every rank initializes the new
# rows identically — FSDP wrap does not set
# sync_module_states=True (see training/distributed.py),
# so without this the new rows would diverge across ranks.
rng_state = torch.get_rng_state()
try:
torch.manual_seed(0)
self.backbone.resize_token_embeddings(_target)
finally:
torch.set_rng_state(rng_state)
if config.freeze_backbone:
logger.info("Freezing Backbone weights...")
for param in self.backbone.parameters():
param.requires_grad = False
# Update dims
if hasattr(self.backbone.config, "hidden_size"):
self.backbone_dim = self.backbone.config.hidden_size
logger.info(f"Backbone hidden dim detected: {self.backbone_dim}")
# We do NOT initialize blocks/head if using backbone
# Resolve any string-valued modality_start_end_token_indices entries
# (e.g. DNA's ("<dna_ref_start>", "<dna_ref_end>")) to integer token
# ids. Unlike time_series's fixed ids (pre-baked into the custom
# interleaved tokenizer's vocab at known positions), DNA's splice
# tokens are authored as literal strings in multimodal.py's prompt
# renderer and in eval_kegg.py — register them as special tokens
# if missing, then resolve to ids so
# _merge_text_input_ids_with_modality_embeds's `input_ids ==
# start_idx` integer comparison works. Mirrors the grow-only,
# seeded-RNG resize pattern above (issue #117) so new embedding
# rows initialize identically across ranks.
if (
self.backbone_tokenizer is not None
and config.modality_start_end_token_indices
):
unresolved = {
modality: tags
for modality, tags in config.modality_start_end_token_indices.items()
if isinstance(tags[0], str) or isinstance(tags[1], str)
}
if unresolved:
missing = sorted(
{
tok
for tags in unresolved.values()
for tok in tags
if isinstance(tok, str)
and tok not in self.backbone_tokenizer.get_vocab()
}
)
if missing:
logger.info(
f"Registering {len(missing)} new special token(s) "
f"{missing} for string-keyed modality_start_end_token_indices entries"
)
num_added = self.backbone_tokenizer.add_special_tokens(
{"additional_special_tokens": missing}
)
if num_added > 0:
rng_state = torch.get_rng_state()
try:
torch.manual_seed(0)
self.backbone.resize_token_embeddings(
len(self.backbone_tokenizer)
)
finally:
torch.set_rng_state(rng_state)
logger.info(
f"Resized token embeddings to {len(self.backbone_tokenizer)} "
f"after adding {num_added} modality special token(s)"
)
resolved = dict(config.modality_start_end_token_indices)
for modality, tags in unresolved.items():
resolved[modality] = tuple(
self.backbone_tokenizer.convert_tokens_to_ids(tok)
if isinstance(tok, str)
else tok
for tok in tags
)
config.modality_start_end_token_indices = resolved
except Exception as e:
logger.error(f"Error loading Backbone {config.llm_backbone_id}: {e}")
self._backbone_load_error = e
raise RuntimeError(
f"Could not load HF backbone {config.llm_backbone_id!r} "
"with local_files_only=True. Stage the model cache before "
"launching or use a config without model.backbone_id. "
f"Current cache directories: {os.environ.get('HF_HOME', 'Not set')}, {os.environ.get('TRANSFORMERS_CACHE', 'Not set')}, {os.environ.get('SHARED_HF_HOME', 'Not set')}"
) from e
# --- Stage 1: Modality Encoders ---
self.encoders = nn.ModuleDict()
self.projectors = nn.ModuleDict()
# Determine target dimension for projectors
target_dim = self.backbone_dim
# === Projector Configuration (from config, with defaults for backward compat) ===
proj_norm_mode = getattr(config, "projector_norm_mode", "layernorm")
proj_target_norm = getattr(config, "projector_target_norm", 0.25)
proj_embed_pos = getattr(config, "projector_modality_embed_pos", "after_norm")
proj_embed_scale = getattr(config, "projector_modality_embed_scale", 0.02)
# Text statistics matching parameters (for match_text_stats and match_text_elemstats modes)
proj_text_norm_mean = getattr(config, "projector_text_norm_mean", 0.25)
proj_text_norm_std = getattr(config, "projector_text_norm_std", 0.05)
proj_text_elem_mean = getattr(config, "projector_text_elem_mean", 0.0)
proj_text_elem_std = getattr(config, "projector_text_elem_std", 0.006)
proj_norm_clip_min = getattr(config, "projector_norm_clip_min", 0.1)
proj_norm_clip_max = getattr(config, "projector_norm_clip_max", 0.5)
# IsoFLOP capacity knobs (single global pair — per-modality variants
# can be added later; for PR-1 the same shape applies to every
# ModalityProjector instance).
proj_hidden_mult = getattr(config, "projector_hidden_mult", 1)
proj_num_layers = getattr(config, "projector_num_layers", 2)
logger.info(
f"Projector config: norm_mode={proj_norm_mode}, target_norm={proj_target_norm}, embed_pos={proj_embed_pos}, embed_scale={proj_embed_scale}, hidden_mult={proj_hidden_mult}, num_layers={proj_num_layers}"
)
if proj_norm_mode in ["match_text_stats", "match_text_elemstats"]:
logger.info(
f" Text stats: norm_mean={proj_text_norm_mean}, norm_std={proj_text_norm_std}, "
f"elem_mean={proj_text_elem_mean}, elem_std={proj_text_elem_std}, clip=[{proj_norm_clip_min}, {proj_norm_clip_max}]"
)
# Text
# Only load external text encoder (SmolLM/etc) if we DO NOT have a backbone.
# If backbone exists, we use its native embedding layer (see _process_multimodal_embeddings).
if Modality.TEXT in config.modalities and self.backbone is None:
logger.info("Initializing External Text Encoder...")
self.encoders["text"] = TextEncoder(d_text=config.d_text)
self.projectors["text"] = ModalityProjector(
config.d_text,
target_dim,
norm_mode=proj_norm_mode,
target_norm=proj_target_norm,
modality_embed_pos=proj_embed_pos,
modality_embed_scale=proj_embed_scale,
text_norm_mean=proj_text_norm_mean,
text_norm_std=proj_text_norm_std,
text_elem_mean=proj_text_elem_mean,
text_elem_std=proj_text_elem_std,
norm_clip_min=proj_norm_clip_min,
norm_clip_max=proj_norm_clip_max,
hidden_mult=proj_hidden_mult,
num_layers=proj_num_layers,
)
# Table
if Modality.TABLE in config.modalities:
self.encoders["table"] = TableEncoder(d_table=config.d_table)
self.projectors["table"] = PerceiverResampler(
input_dim=config.d_table,
d_model=target_dim,
num_latents=32,
num_layers=2,
)
# Time Series
if Modality.TIME_SERIES in config.modalities:
self.encoders["time_series"] = TimeSeriesEncoder(
encoder_type=config.ts_projector,
d_ts=config.d_ts,
num_vars=config.ts_variates,
model_name=config.ts_encoder_id,
max_ts_length=config.max_ts_length,
is_interleaved=bool(self.config.is_interleaved_qa),
intern_s2_sampling_rate=config.intern_s2_sampling_rate,
timeomni_patch_len=config.timeomni_patch_len,
timeomni_stride=config.timeomni_stride,
timeomni_d_model=config.timeomni_d_model,
timeomni_dropout=config.timeomni_dropout,
timeomni_ts_tokens=config.timeomni_ts_tokens,
timeomni_max_patches=config.timeomni_max_patches,
load_pretrained=config.ts_load_pretrained,
)
# Use actual encoder output dim if available (Moirai might be 1024, config 512)
ts_input_dim = getattr(self.encoders["time_series"], "hidden_dim", config.d_ts)
self.projectors["time_series"] = ModalityProjector(
ts_input_dim,
target_dim,
hidden_mult=proj_hidden_mult,
num_layers=proj_num_layers,
)
# Image
if Modality.IMAGE in config.modalities:
self.encoders["image"] = ImageEncoder(
d_img=config.d_img,
model_name=config.image_encoder_id,
)
self.projectors["image"] = ModalityProjector(
config.d_img,
target_dim,
norm_mode=proj_norm_mode,
target_norm=proj_target_norm,
modality_embed_pos=proj_embed_pos,
modality_embed_scale=proj_embed_scale,
text_norm_mean=proj_text_norm_mean,
text_norm_std=proj_text_norm_std,
text_elem_mean=proj_text_elem_mean,
text_elem_std=proj_text_elem_std,
norm_clip_min=proj_norm_clip_min,
norm_clip_max=proj_norm_clip_max,
hidden_mult=proj_hidden_mult,
num_layers=proj_num_layers,
)
# Geometry
if Modality.GEOMETRY in config.modalities:
self.encoders["geometry"] = GeometryEncoder(d_geo=config.d_geo)
geo_input_dim = getattr(self.encoders["geometry"], "hidden_dim", config.d_geo)
self.projectors["geometry"] = PerceiverResampler(
input_dim=geo_input_dim,
d_model=target_dim,
num_latents=32,
num_layers=2,
)
# Graph (requires torch_geometric)
if Modality.GRAPH in config.modalities:
self.encoders["graph"] = GraphEncoder(input_dim=32, d_graph=config.d_graph)
self.projectors["graph"] = PerceiverResampler(
input_dim=config.d_graph, d_model=target_dim, num_latents=32, num_layers=2
)
# DNA (Nucleotide Transformer / Evo2)
if Modality.DNA in config.modalities:
dna_model_name = getattr(
config,
"dna_model_name",
"InstaDeepAI/nucleotide-transformer-2.5b-multi-species",
)
dna_is_evo2 = getattr(config, "dna_is_evo2", False)
self.encoders["dna"] = DNAEncoder(
d_dna=config.d_dna,
model_name=dna_model_name,
dna_is_evo2=dna_is_evo2,
max_dna_length=getattr(config, "max_dna_length", None),
)
# Output dimension from the encoder (d_dna after its internal projection)
dna_input_dim = getattr(self.encoders["dna"], "hidden_dim", config.d_dna)
self.projectors["dna"] = ModalityProjector(
dna_input_dim,
target_dim,
norm_mode=proj_norm_mode,
target_norm=proj_target_norm,
modality_embed_pos=proj_embed_pos,
modality_embed_scale=proj_embed_scale,
text_norm_mean=proj_text_norm_mean,
text_norm_std=proj_text_norm_std,
text_elem_mean=proj_text_elem_mean,
text_elem_std=proj_text_elem_std,
norm_clip_min=proj_norm_clip_min,
norm_clip_max=proj_norm_clip_max,
hidden_mult=proj_hidden_mult,
num_layers=proj_num_layers,
)
# === Output decoders (Phase 1) ===
# self.decoders is the config-driven home for output decoders owned by
# this module (currently just text; Phase 2+ adds time_series, etc.).
# The VLA action decoder is the one legacy exception — it stays as
# self.action_head (built in the VLA block below) because the VLA
# trainer and existing checkpoints hard-code the `action_head.*`
# parameter name.
self.decoders = nn.ModuleDict()
decoder_cfgs = config.decoder_configs or {}
for _dec_name in config.output_decoders:
if _dec_name == "text":
# Parameter-less on the HF-backbone path (the LM head lives in
# the backbone); carries the shifted-CE loss.
self.decoders["text"] = LMHeadDecoder()
elif _dec_name in ("action", "regression"):
# Owned by the VLA block as self.action_head — skip here to
# avoid double-registering parameters.
continue
elif _dec_name == "time_series":
# Direct multi-horizon quantile forecaster. Reads pooled
# backbone hidden states; defaults pull from the time-series
# model config so a bare ["text","time_series"] works.
ts_cfg = dict(decoder_cfgs.get("time_series", {}))
if ts_cfg.get("generator") is not None:
# Keep native nesting: injecting flat defaults would mix
# the legacy and explicit constructor contracts.
if isinstance(ts_cfg["generator"], Mapping):
generator_cfg = dict(ts_cfg["generator"])
generator_cfg.setdefault("horizon", config.ts_forecast_horizon)
generator_cfg.setdefault("num_vars", config.ts_variates)
ts_cfg["generator"] = generator_cfg
else:
ts_cfg.setdefault("horizon", config.ts_forecast_horizon)
ts_cfg.setdefault("num_vars", config.ts_variates)
self.decoders["time_series"] = TimeSeriesDecoder(
d_model=target_dim, **ts_cfg
)
elif _dec_name == "image":
self.decoders["image"] = ImageDecoder(
d_model=target_dim, **dict(decoder_cfgs.get("image", {}))
)
elif _dec_name == "geometry":
# Field-regression head (inverse of GeometryEncoder/Walrus).
# num_points/num_channels are field-specific — must be given in
# decoder_configs["geometry"].
geo_cfg = dict(decoder_cfgs.get("geometry", {}))
if "num_points" not in geo_cfg or "num_channels" not in geo_cfg:
raise ValueError(
"geometry decoder requires decoder_configs['geometry'] "
"with 'num_points' and 'num_channels'."
)
self.decoders["geometry"] = GeometryDecoder(
d_model=target_dim, **geo_cfg
)
elif _dec_name == "graph":
# Per-node head (inverse of GraphEncoder/GraphMAE2) — node
# feature/property prediction only, never structure generation.
# out_dim is task-specific — must be given in
# decoder_configs["graph"].
graph_cfg = dict(decoder_cfgs.get("graph", {}))
if "out_dim" not in graph_cfg:
raise ValueError(
"graph decoder requires decoder_configs['graph'] with "
"'out_dim' (and optionally task='regression'|'classification')."
)
self.decoders["graph"] = GraphDecoder(d_model=target_dim, **graph_cfg)
else:
raise ValueError(
f"Unknown output decoder '{_dec_name}'. Known: "
f"{sorted(DECODERS)} (additional decoders land in Phase 2+)."
)
# self.text_decoder is the forward path's handle on the text decoder.
# Always present so the non-VLA path works even if a config omits
# "text" from output_decoders.
if "text" not in self.decoders:
self.decoders["text"] = LMHeadDecoder()
self.text_decoder = self.decoders["text"]
if self.is_vla:
if self.backbone is None:
raise RuntimeError(
f"VLA mode requires a loadable llm_backbone_id. "
f"backbone_id={config.llm_backbone_id}, error={self._backbone_load_error}"
)
if Modality.IMAGE not in config.modalities:
raise RuntimeError("VLA mode requires 'image' in model.modalities")
self.pose_embed = nn.Sequential(
nn.Linear(config.pose_dim, target_dim),
nn.ReLU(),
nn.Linear(target_dim, target_dim),
)
self.pose_modality_embedding = nn.Parameter(torch.randn(1, 1, target_dim) * 0.02)
# Action regression head, now expressed via the OutputDecoder
# registry. Same MLP (Linear->ReLU->Linear) and init order as the
# old inline nn.Sequential, so numerics are unchanged. The attribute
# keeps the name `action_head` so the VLA trainer and existing
# checkpoints keep working; the inner MLP moves from `action_head.*`
# to `action_head.head.*`.
self.action_head = RegressionDecoder(target_dim, config.action_dim)
# Freeze Encoders if requested (Zone 1)
if config.freeze_encoders:
logger.info("Freezing Modality Encoders...")
for param in self.encoders.parameters():
param.requires_grad = False
# Cache frozen state for each encoder (avoids O(params) check in forward)
self._encoder_frozen_cache = {
modality: not any(p.requires_grad for p in encoder.parameters())
for modality, encoder in self.encoders.items()
}
# --- Stage 3: Unified Transformer (Legacy / Custom) ---
if self.backbone is None:
self.blocks = nn.ModuleList(
[TransformerBlock(config) for _ in range(config.num_layers)]
)
self.ln_f = nn.LayerNorm(config.d_model)
# RoPE
self.rope = RotaryEmbedding(config.d_model // config.num_heads)
# --- Stage 4: Output Head ---
self.head = CausalLMHead(config.d_model, config.vocab_size)
def get_input_embeddings(self, inputs):
"""Helper to get embeddings from varied inputs."""
# Retrieve input_ids from 'text' if available
if "text" in inputs:
if self.backbone:
return self.backbone.get_input_embeddings()(inputs["text"])
else:
# Custom implementation doesn't have a separate embedding layer usually stored here
# In custom impl, Encoders handle embedding.
# However, for text, TextEncoder output IS the embedding.
pass
return None
def _resolve_pad_id(self) -> int | None:
"""Resolve pad_token_id from whichever tokenizer is attached.
`backbone_tokenizer` is set only on Path A (HF backbone load).
`tokenizer` is set unconditionally by src/train.py:642 for both
paths. Prefer backbone_tokenizer when present (avoids a mismatch if
Path A loads a backbone with its own tokenizer that differs from
the training tokenizer), skipping any tokenizer whose
`pad_token_id` is None, and fall back to the training tokenizer so
Path B's pad-mask actually engages.
"""
for attr in ("backbone_tokenizer", "tokenizer"):
tok = getattr(self, attr, None)
if tok is not None:
pad_id = getattr(tok, "pad_token_id", None)
if pad_id is not None:
return pad_id
return None
def _process_multimodal_embeddings(self, inputs):
"""Encodes and projects all modalities into a list of (name, tensor).
Args:
inputs: Dict mapping modality name to input tensor.
Returns:
List of (modality_name, projected_embedding) tuples.
"""
embeddings = []
self._modality_pad_masks = {}
for modality in self.config.modalities:
if modality in inputs:
# Special handling for text if backbone is present
if modality == "text" and self.backbone is not None:
# Use backbone's own embedding layer directly
# This ensures tokenizer compatibility (e.g. OLMo input -> OLMo embedding)
embed_layer = self.backbone.get_input_embeddings()
projected = embed_layer(inputs[modality])
# --- Text-Only Dropout (Molmo Paper) ---
# Dropping entire text tokens (masking) to force reliance on image.
# Only apply during training.
if self.training and getattr(self.config, "text_dropout", 0.0) > 0.0:
mask_prob = self.config.text_dropout
# Token-level dropout (Molmo paper): zero entire text token vectors
# to force reliance on image/modality tokens during training.
# mask shape: (B, T_text, 1) — broadcasts over embedding dim
mask = torch.bernoulli(
torch.ones_like(projected[:, :, :1]) * (1 - mask_prob)
)
projected = projected * mask
# Alternative: element-wise dropout (may suit non-VLM modalities)
# projected = F.dropout(projected, p=mask_prob, training=True)
# ---------------------------------------
embeddings.append((modality, projected))
continue
# DNA: reference/variant sequences arrive as two independent
# sub-inputs under one "dna" entry. They share the single
# DNAEncoder/projector registered above, but each gets encoded
# and projected separately (early fusion) and emitted as its
# own (name, embedding) entry — "dna_reference"/"dna_variant"
# — so the merge step below can splice each into its own
# token span (see _PARENT_MODALITY in
# _merge_text_input_ids_with_modality_embeds).
if modality == Modality.DNA and isinstance(inputs[modality], dict):
raw_features = inputs[modality]
if "dna_reference" in raw_features and "dna_variant" in raw_features:
for sub_modality in ("dna_reference", "dna_variant"):
feature = raw_features[sub_modality]
if (
isinstance(feature, list | tuple)
and len(feature) == 2
and all(isinstance(x, torch.Tensor) for x in feature)
):
encoder_input = {
"input_ids": feature[0],
"attention_mask": feature[1],
}
elif isinstance(feature, list | tuple) and len(feature) == 1:
encoder_input = feature[0]
else:
encoder_input = feature
sub_encoded = self.encoders[modality](encoder_input)
if getattr(self, "_encoder_frozen_cache", {}).get(modality, False):
sub_encoded = sub_encoded.detach()
try:
projected = self.projectors[modality](sub_encoded)
except Exception as e:
logger.error(f"Error projecting {sub_modality}: {e}")
logger.error(f"Feature Shape: {sub_encoded.shape}")
logger.error(f"Projector: {self.projectors[modality]}")
raise e
embeddings.append((sub_modality, projected))
continue # dna_reference/dna_variant handled above; skip the generic path below
# 1. Encode
# Forward through encoder unconditionally for static_graph compatibility.
# Detach output of frozen encoders to prevent autograd graph building through them.
# This achieves the same memory/compute savings as torch.no_grad() without
# changing the forward graph structure (which breaks DDP static_graph).
encoder_input = inputs[modality]
reference_shape = None
reference_valid = None
if modality == "image" and encoder_input.ndim == 5:
reference_shape = encoder_input.shape[:2]
reference_valid = inputs.get("image_mask")
if reference_valid is None:
reference_valid = torch.ones(reference_shape, device=encoder_input.device, dtype=torch.bool)
if reference_valid.shape != reference_shape or not torch.all((reference_valid == 0) | (reference_valid == 1)):
raise ValueError("image_mask must be binary with shape (B, N)")
reference_valid = reference_valid.to(device=encoder_input.device, dtype=torch.bool).flatten()
if not reference_valid.any():
continue
# Padding must not affect projector batch statistics or
# consume encoder work, even before the sequence is merged.
encoder_input = encoder_input.flatten(0, 1)[reference_valid]
features = self.encoders[modality](encoder_input)
pad_mask = getattr(self.encoders[modality], "_last_pad_mask", None)
# Detach if encoder is frozen (avoids backward through encoder)
# Use cached frozen state to avoid O(params) check every forward
if getattr(self, "_encoder_frozen_cache", {}).get(modality, False):
features = features.detach()
# 2. Project
try:
projected = self.projectors[modality](features)
except Exception as e:
logger.error(f"Error projecting {modality}: {e}")
logger.error(f"Feature Shape: {features.shape}")
logger.error(f"Projector: {self.projectors[modality]}")
raise e
if reference_shape is not None:
per_reference, width = projected.shape[1:]
scattered = projected.new_zeros((reference_shape[0] * reference_shape[1], per_reference, width))
scattered[reference_valid.to(projected.device)] = projected
projected = scattered.reshape(reference_shape[0], reference_shape[1] * per_reference, width)
if pad_mask is not None:
if pad_mask.shape != projected.shape[:2]:
raise ValueError(
f"{modality} pad mask shape {tuple(pad_mask.shape)} does not "
f"match projected features {tuple(projected.shape)}"
)
self._modality_pad_masks[modality] = pad_mask.detach()
embeddings.append((modality, projected))
return embeddings
def _build_prefix_content_mask(
self, embeddings: list[tuple[str, torch.Tensor]]
) -> torch.Tensor:
"""Build a per-sample valid-token mask in concatenated prefix order."""
masks = []
for modality, features in embeddings:
pad_mask = getattr(self, "_modality_pad_masks", {}).get(modality)
if pad_mask is None:
valid = torch.ones(
features.shape[:2], dtype=torch.bool, device=features.device
)
else:
if pad_mask.shape != features.shape[:2]:
raise ValueError(
f"{modality} pad mask shape {tuple(pad_mask.shape)} does not "
f"match features {tuple(features.shape)}"
)
valid = ~pad_mask.to(device=features.device, dtype=torch.bool)
masks.append(valid)
if not masks:
raise ValueError("Cannot build a content mask without embeddings")
return torch.cat(masks, dim=1)
def _merge_text_input_ids_with_modality_embeds(
self,
input_ids,
input_embeds,
embeddings_list,
metadata,
pad_id=None,
modality_pad_masks=None,
):
"""
Replaces the special modality tokens in input_ids with the corresponding
modality features, and returns merged embeddings and masks.
Args:
embeddings_list: List of (modality_name, embedding_tensor) tuples. Includes text modality embeddings.
labels: Optional labels aligned with input_ids (text tokens only).
pad_id: Optional pad token id used to drop padding from the merge.
Returns:
final_embedding: (B, T_total, D_model)
final_attention_mask: (B, T_total)
position_ids: (B, T_total)
final_labels: (B, T_total) or None
"""
embeddings_by_modality = {m: e for m, e in embeddings_list}
if "text" not in embeddings_by_modality:
raise ValueError("Interleaving requires text embeddings to be present.")
batch_size, sequence_length = input_ids.shape
embed_dim = input_embeds.shape[-1]
start_any = torch.zeros_like(input_ids, dtype=torch.bool)
end_any = torch.zeros_like(input_ids, dtype=torch.bool)
start_modality_idx = torch.full_like(input_ids, -1, dtype=torch.long)
modalities = []
# DNA sub-modalities (dna_reference, dna_variant) are keyed under the
# parent "dna" entry in config.modalities/self.encoders — they get
# their own start/end token pair (see modality_start_end_token_indices)
# but share the single DNAEncoder/projector instance and the
# config.modalities/["dna"] gate.
_PARENT_MODALITY = {"dna_reference": "dna", "dna_variant": "dna"}
for modality, (start_idx, end_idx) in (
self.config.modality_start_end_token_indices or {}
).items():
parent_modality = _PARENT_MODALITY.get(modality, modality)
if parent_modality not in self.config.modalities or modality == "text":
continue
if modality not in embeddings_by_modality:
raise ValueError(f"Missing embeddings for modality '{modality}'.")
start_mask = input_ids == start_idx
end_mask = input_ids == end_idx
if (start_any & start_mask).any() or (end_any & end_mask).any():
raise ValueError("Overlapping modality start/end tokens detected.")