jasonzhango commited on
Commit
904b1fe
·
verified ·
1 Parent(s): d3dc538

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -34,3 +34,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  checkpoint-100000/trainer_state.json filter=lfs diff=lfs merge=lfs -text
 
 
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  checkpoint-100000/trainer_state.json filter=lfs diff=lfs merge=lfs -text
37
+ checkpoint-50000/trainer_state.json filter=lfs diff=lfs merge=lfs -text
checkpoint-50000/added_tokens.json ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</box>": 151677,
3
+ "</img>": 151670,
4
+ "</quad>": 151673,
5
+ "</ref>": 151675,
6
+ "</think>": 151668,
7
+ "</tool_call>": 151658,
8
+ "</tool_response>": 151666,
9
+ "<IMG_CONTEXT>": 151671,
10
+ "<box>": 151676,
11
+ "<img>": 151669,
12
+ "<quad>": 151672,
13
+ "<ref>": 151674,
14
+ "<think>": 151667,
15
+ "<tool_call>": 151657,
16
+ "<tool_response>": 151665,
17
+ "<|action_end|>": 151680,
18
+ "<|action_pad|>": 151679,
19
+ "<|action_pass|>": 151681,
20
+ "<|action_start|>": 151678,
21
+ "<|box_end|>": 151649,
22
+ "<|box_start|>": 151648,
23
+ "<|endoftext|>": 151643,
24
+ "<|file_sep|>": 151664,
25
+ "<|fim_middle|>": 151660,
26
+ "<|fim_pad|>": 151662,
27
+ "<|fim_prefix|>": 151659,
28
+ "<|fim_suffix|>": 151661,
29
+ "<|im_end|>": 151645,
30
+ "<|im_start|>": 151644,
31
+ "<|image_pad|>": 151655,
32
+ "<|object_ref_end|>": 151647,
33
+ "<|object_ref_start|>": 151646,
34
+ "<|quad_end|>": 151651,
35
+ "<|quad_start|>": 151650,
36
+ "<|repo_name|>": 151663,
37
+ "<|state_end|>": 151684,
38
+ "<|state_pad|>": 151683,
39
+ "<|state_start|>": 151682,
40
+ "<|video_pad|>": 151656,
41
+ "<|vision_end|>": 151653,
42
+ "<|vision_pad|>": 151654,
43
+ "<|vision_start|>": 151652,
44
+ "<|vla|>": 151685
45
+ }
checkpoint-50000/chat_template.jinja ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {% for message in messages %}{{'<|im_start|>' + message['role'] + '
2
+ '}}{% if message['content'] is string %}{{ message['content'] }}{% else %}{% for content in message['content'] %}{% if content['type'] == 'image' %}{{ '<image>
3
+ ' }}{% elif content['type'] == 'video' %}{{ '<video>
4
+ ' }}{% elif content['type'] == 'text' %}{{ content['text'] }}{% endif %}{% endfor %}{% endif %}{{'<|im_end|>
5
+ '}}{% endfor %}{% if add_generation_prompt %}{{'<|im_start|>assistant
6
+ ' }}{% endif %}
checkpoint-50000/config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "action_chunk_size": 30,
3
+ "action_pass_id": 151681,
4
+ "action_token_id": 151679,
5
+ "architectures": [
6
+ "EO1InternVLPiFlowMatchingModel"
7
+ ],
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_eo1_internvl.EO1InternVLPiFlowMatchingConfig",
10
+ "AutoModel": "modeling_eo1_internvl.EO1InternVLPiFlowMatchingModel"
11
+ },
12
+ "backbone_name_or_path": "hugg_model/InternVL3_5-1B",
13
+ "dtype": "bfloat16",
14
+ "eos_token_id": 151645,
15
+ "expert_hidden_size": 1024,
16
+ "expert_init_from_backbone": false,
17
+ "expert_intermediate_size": 3072,
18
+ "expert_layer_mapping": "last",
19
+ "expert_num_attention_heads": 16,
20
+ "expert_num_hidden_layers": 18,
21
+ "ignore_index": -100,
22
+ "img_context_token_id": 151671,
23
+ "max_action_dim": 32,
24
+ "model_type": "eo1_internvl_pi",
25
+ "num_denoise_steps": 10,
26
+ "pad_token_id": 151643,
27
+ "transformers_version": "4.56.0"
28
+ }
checkpoint-50000/configuration_eo1_internvl.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 EO-Robotics Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ from transformers.configuration_utils import PretrainedConfig
18
+
19
+
20
+ class EO1InternVLPiFlowMatchingConfig(PretrainedConfig):
21
+ """
22
+ EO1 Flow-Matching wrapper for InternVL backbone + Pi05-style action expert.
23
+
24
+ Pi05 key properties (mirrors `openpi.models.pi0` with `pi05=True`):
25
+ - Prefix uses standard *causal* LM forward (flash-attn friendly) to build a per-layer KV cache.
26
+ - Action block is bidirectional within itself and can attend to the cached prefix KV.
27
+ - Flow-matching timestep is injected via AdaRMSNorm in the action expert (not concatenated into embeddings).
28
+ - Continuous state token in suffix is *disabled* (state should be encoded in text if needed).
29
+ """
30
+
31
+ model_type = "eo1_internvl_pi"
32
+ keys_to_ignore_at_inference = ["past_key_values"]
33
+
34
+ def __init__(
35
+ self,
36
+ backbone_name_or_path: str | None = None,
37
+ # Flow matching
38
+ action_chunk_size: int = 16,
39
+ max_action_dim: int = 32,
40
+ num_denoise_steps: int = 10,
41
+ # Tokens
42
+ action_token_id: int | None = None,
43
+ action_pass_id: int | None = None,
44
+ img_context_token_id: int | None = None,
45
+ ignore_index: int = -100,
46
+ # Expert init
47
+ expert_init_from_backbone: bool = False,
48
+ # Expert architecture (Pi05-style: smaller action expert than VLM)
49
+ expert_num_hidden_layers: int | None = 18,
50
+ expert_hidden_size: int | None = 1024,
51
+ expert_intermediate_size: int | None = 3072,
52
+ expert_num_attention_heads: int | None = 16,
53
+ expert_layer_mapping: str = "last",
54
+ **kwargs,
55
+ ):
56
+ self.backbone_name_or_path = backbone_name_or_path
57
+
58
+ self.action_chunk_size = int(action_chunk_size)
59
+ self.max_action_dim = int(max_action_dim)
60
+ self.num_denoise_steps = int(num_denoise_steps)
61
+
62
+ self.action_token_id = action_token_id
63
+ self.action_pass_id = action_pass_id
64
+ self.img_context_token_id = img_context_token_id
65
+ self.ignore_index = int(ignore_index)
66
+
67
+ self.expert_init_from_backbone = bool(expert_init_from_backbone)
68
+ self.expert_num_hidden_layers = None if expert_num_hidden_layers is None else int(expert_num_hidden_layers)
69
+ self.expert_hidden_size = None if expert_hidden_size is None else int(expert_hidden_size)
70
+ self.expert_intermediate_size = None if expert_intermediate_size is None else int(expert_intermediate_size)
71
+ self.expert_num_attention_heads = None if expert_num_attention_heads is None else int(expert_num_attention_heads)
72
+ self.expert_layer_mapping = str(expert_layer_mapping)
73
+
74
+ super().__init__(**kwargs)
75
+
76
+
77
+ EO1InternVLPiFlowMatchingConfig.register_for_auto_class()
checkpoint-50000/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
checkpoint-50000/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cf0bcc67c09a3a44336ddfedb7ab1d6f92c16bc3bfa28a2ea8813dfe211219ab
3
+ size 3726487744
checkpoint-50000/modeling_eo1_internvl.py ADDED
@@ -0,0 +1,1205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 EO-Robotics Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import copy
18
+ import math
19
+ import os
20
+ from dataclasses import dataclass
21
+ from typing import Any
22
+
23
+ import torch
24
+ import torch.nn as nn
25
+ import torch.nn.functional as F # noqa: N812
26
+ from torch import Tensor
27
+ from transformers.modeling_outputs import ModelOutput
28
+ from transformers.modeling_utils import PreTrainedModel
29
+ from transformers.utils import logging
30
+
31
+ from .configuration_eo1_internvl import EO1InternVLPiFlowMatchingConfig
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ def create_sinusoidal_pos_embedding(
38
+ time: torch.tensor,
39
+ dimension: int,
40
+ min_period: float = 4e-3,
41
+ max_period: float = 4.0,
42
+ device: str | torch.device = "cpu",
43
+ ) -> Tensor:
44
+ """Sine-cosine embedding for scalar time in [0,1]. Matches openpi `posemb_sincos` sensitivity."""
45
+ if dimension % 2 != 0:
46
+ raise ValueError(f"dimension ({dimension}) must be divisible by 2")
47
+ if time.ndim != 1:
48
+ raise ValueError("The time tensor is expected to be of shape `(batch_size, )`.")
49
+
50
+ fraction = torch.linspace(0.0, 1.0, dimension // 2, device=device)
51
+ period = min_period * (max_period / min_period) ** fraction
52
+ scaling_factor = 1.0 / period * 2 * math.pi
53
+ sin_input = scaling_factor[None, :] * time[:, None]
54
+ return torch.cat([torch.sin(sin_input), torch.cos(sin_input)], dim=1)
55
+
56
+
57
+ def _masked_fill_min(x: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
58
+ """Fill with dtype-min where mask is False. `mask` is broadcastable to `x`."""
59
+ return x.masked_fill(~mask, torch.finfo(x.dtype).min)
60
+
61
+
62
+ class AdaRMSNorm(nn.Module):
63
+ """
64
+ Pi05-style AdaRMSNorm (openpi `gemma.RMSNorm` with `cond!=None`):
65
+ - RMS normalize in float32
66
+ - per-layer modulation = Linear(cond -> 3*D) initialized to zeros
67
+ - output = normed * (1 + scale) + shift
68
+ - returns gate for gated residual.
69
+ """
70
+
71
+ def __init__(self, dim: int, *, eps: float = 1e-6):
72
+ super().__init__()
73
+ self.eps = float(eps)
74
+ self.modulation = nn.Linear(dim, dim * 3, bias=True)
75
+ nn.init.zeros_(self.modulation.weight)
76
+ nn.init.zeros_(self.modulation.bias)
77
+
78
+ def forward(self, x: torch.Tensor, cond: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
79
+ if cond is None:
80
+ raise ValueError("AdaRMSNorm requires `cond` (Pi05 mode).")
81
+ if cond.ndim != 2:
82
+ raise ValueError(f"cond must be (B,D), got {tuple(cond.shape)}")
83
+ if x.ndim != 3:
84
+ raise ValueError(f"x must be (B,T,D), got {tuple(x.shape)}")
85
+ if x.shape[0] != cond.shape[0]:
86
+ raise ValueError(f"Batch mismatch: {x.shape[0]=} vs {cond.shape[0]=}")
87
+ if x.shape[-1] != cond.shape[-1]:
88
+ raise ValueError(f"Dim mismatch: {x.shape[-1]=} vs {cond.shape[-1]=}")
89
+
90
+ x_dtype = x.dtype
91
+ x_f32 = x.float()
92
+ var = x_f32.pow(2).mean(dim=-1, keepdim=True)
93
+ normed = x_f32 * torch.rsqrt(var + self.eps)
94
+
95
+ mod = self.modulation(cond).to(dtype=x_f32.dtype)
96
+ scale, shift, gate = mod.chunk(3, dim=-1)
97
+ scale = scale[:, None, :]
98
+ shift = shift[:, None, :]
99
+ gate = gate[:, None, :]
100
+ out = normed * (1 + scale) + shift
101
+ return out.to(dtype=x_dtype), gate.to(dtype=x_dtype)
102
+
103
+
104
+ class Qwen2PiSelfAttention(nn.Module):
105
+ """
106
+ Qwen2 attention variant for Pi05 action expert:
107
+ - queries from suffix tokens (action tokens)
108
+ - keys/values from concat(prefix_kv_cache, suffix_kv)
109
+ - uses full (non-causal) attention mask provided by caller.
110
+ """
111
+
112
+ def __init__(self, qwen_config: Any, layer_idx: int):
113
+ super().__init__()
114
+ try:
115
+ from transformers.models.qwen2.modeling_qwen2 import apply_rotary_pos_emb, repeat_kv
116
+ except Exception as e: # pragma: no cover
117
+ raise ImportError("transformers qwen2 internals are required for eo_pi_internvl.") from e
118
+
119
+ self._apply_rotary_pos_emb = apply_rotary_pos_emb
120
+ self._repeat_kv = repeat_kv
121
+
122
+ self.layer_idx = int(layer_idx)
123
+ self.hidden_size = int(qwen_config.hidden_size)
124
+ self.num_heads = int(qwen_config.num_attention_heads)
125
+ self.num_kv_heads = int(qwen_config.num_key_value_heads)
126
+ self.num_kv_groups = self.num_heads // self.num_kv_heads
127
+ self.head_dim = int(getattr(qwen_config, "head_dim", self.hidden_size // self.num_heads))
128
+ self.scaling = self.head_dim**-0.5
129
+
130
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
131
+ self.k_proj = nn.Linear(self.hidden_size, self.num_kv_heads * self.head_dim, bias=True)
132
+ self.v_proj = nn.Linear(self.hidden_size, self.num_kv_heads * self.head_dim, bias=True)
133
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
134
+
135
+ def forward(
136
+ self,
137
+ hidden_states: torch.Tensor,
138
+ *,
139
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
140
+ attention_mask: torch.Tensor | None,
141
+ prefix_k: torch.Tensor,
142
+ prefix_v: torch.Tensor,
143
+ ) -> torch.Tensor:
144
+ # hidden_states: (B, S, D)
145
+ bsz, seqlen, _ = hidden_states.shape
146
+ q = self.q_proj(hidden_states).view(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2)
147
+ k = self.k_proj(hidden_states).view(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2)
148
+ v = self.v_proj(hidden_states).view(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2)
149
+
150
+ cos, sin = position_embeddings
151
+ q, k = self._apply_rotary_pos_emb(q, k, cos, sin)
152
+
153
+ if prefix_k.ndim != 4 or prefix_v.ndim != 4:
154
+ raise ValueError(f"prefix_k/v must be (B, n_kv, P, hd), got {tuple(prefix_k.shape)}, {tuple(prefix_v.shape)}")
155
+ if int(prefix_k.shape[0]) != bsz or int(prefix_v.shape[0]) != bsz:
156
+ raise ValueError("prefix_k/v batch mismatch.")
157
+ if int(prefix_k.shape[1]) != self.num_kv_heads or int(prefix_v.shape[1]) != self.num_kv_heads:
158
+ raise ValueError(
159
+ "prefix_k/v num_kv_heads mismatch: "
160
+ f"{int(prefix_k.shape[1])=} {int(prefix_v.shape[1])=} vs {self.num_kv_heads=}"
161
+ )
162
+ if int(prefix_k.shape[-1]) != self.head_dim or int(prefix_v.shape[-1]) != self.head_dim:
163
+ raise ValueError("prefix_k/v head_dim mismatch.")
164
+
165
+ k_all = torch.cat([prefix_k, k], dim=2) # (B, n_kv, P+S, hd)
166
+ v_all = torch.cat([prefix_v, v], dim=2)
167
+
168
+ k_all = self._repeat_kv(k_all, self.num_kv_groups) # (B, n_heads, P+S, hd)
169
+ v_all = self._repeat_kv(v_all, self.num_kv_groups)
170
+
171
+ # attention_mask: (B, 1, S, P+S) additive (0 or -inf), broadcast to heads
172
+ if attention_mask is not None:
173
+ if attention_mask.ndim != 4:
174
+ raise ValueError(f"attention_mask must be 4D (B,1,S,K), got {tuple(attention_mask.shape)}")
175
+ attn_mask = attention_mask.expand(bsz, self.num_heads, seqlen, k_all.shape[-2])
176
+ else:
177
+ attn_mask = None
178
+
179
+ attn_out = torch.nn.functional.scaled_dot_product_attention(
180
+ q, k_all, v_all, attn_mask=attn_mask, dropout_p=0.0, is_causal=False
181
+ ) # (B, n_heads, S, hd)
182
+ attn_out = attn_out.transpose(1, 2).contiguous().view(bsz, seqlen, self.num_heads * self.head_dim)
183
+ return self.o_proj(attn_out)
184
+
185
+
186
+ class Qwen2PiMLP(nn.Module):
187
+ def __init__(self, qwen_config: Any):
188
+ super().__init__()
189
+ hidden = int(qwen_config.hidden_size)
190
+ inter = int(qwen_config.intermediate_size)
191
+ self.gate_proj = nn.Linear(hidden, inter, bias=False)
192
+ self.up_proj = nn.Linear(hidden, inter, bias=False)
193
+ self.down_proj = nn.Linear(inter, hidden, bias=False)
194
+ act_name = str(getattr(qwen_config, "hidden_act", "silu"))
195
+ if act_name != "silu":
196
+ logger.warning_once("EO Pi action expert: forcing SiLU hidden_act for MLP (got %s).", act_name)
197
+ self.act = nn.SiLU()
198
+
199
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
200
+ return self.down_proj(self.act(self.gate_proj(x)) * self.up_proj(x))
201
+
202
+
203
+ class Qwen2PiDecoderLayer(nn.Module):
204
+ def __init__(self, qwen_config: Any, layer_idx: int):
205
+ super().__init__()
206
+ eps = float(getattr(qwen_config, "rms_norm_eps", 1e-6))
207
+ self.input_layernorm = AdaRMSNorm(int(qwen_config.hidden_size), eps=eps)
208
+ self.self_attn = Qwen2PiSelfAttention(qwen_config=qwen_config, layer_idx=layer_idx)
209
+ self.post_attention_layernorm = AdaRMSNorm(int(qwen_config.hidden_size), eps=eps)
210
+ self.mlp = Qwen2PiMLP(qwen_config=qwen_config)
211
+
212
+ def forward(
213
+ self,
214
+ hidden_states: torch.Tensor,
215
+ *,
216
+ adarms_cond: torch.Tensor,
217
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
218
+ attention_mask: torch.Tensor | None,
219
+ prefix_k: torch.Tensor,
220
+ prefix_v: torch.Tensor,
221
+ ) -> torch.Tensor:
222
+ residual = hidden_states
223
+ x, gate = self.input_layernorm(hidden_states, adarms_cond)
224
+ x = self.self_attn(
225
+ x,
226
+ position_embeddings=position_embeddings,
227
+ attention_mask=attention_mask,
228
+ prefix_k=prefix_k,
229
+ prefix_v=prefix_v,
230
+ )
231
+ hidden_states = residual + x * gate
232
+
233
+ residual = hidden_states
234
+ x, gate = self.post_attention_layernorm(hidden_states, adarms_cond)
235
+ x = self.mlp(x)
236
+ hidden_states = residual + x * gate
237
+ return hidden_states
238
+
239
+
240
+ class Qwen2PiActionExpert(nn.Module):
241
+ def __init__(self, qwen_config: Any, *, init_from_qwen2_lm: nn.Module | None = None):
242
+ super().__init__()
243
+ try:
244
+ from transformers.models.qwen2.modeling_qwen2 import Qwen2RotaryEmbedding
245
+ except Exception as e: # pragma: no cover
246
+ raise ImportError("transformers qwen2 internals are required for eo_pi_internvl.") from e
247
+
248
+ self.config = qwen_config
249
+ self.num_layers = int(qwen_config.num_hidden_layers)
250
+ self.layers = nn.ModuleList([Qwen2PiDecoderLayer(qwen_config, i) for i in range(self.num_layers)])
251
+ self.rotary_emb = Qwen2RotaryEmbedding(qwen_config)
252
+ self.final_norm = AdaRMSNorm(int(qwen_config.hidden_size), eps=float(getattr(qwen_config, "rms_norm_eps", 1e-6)))
253
+
254
+ if init_from_qwen2_lm is not None:
255
+ self._init_from_qwen2_lm(init_from_qwen2_lm)
256
+
257
+ def _init_from_qwen2_lm(self, qwen2_lm: nn.Module):
258
+ """
259
+ Copy attention/MLP weights from a Qwen2ForCausalLM (or Qwen2Model) into this expert.
260
+ AdaRMSNorm modulation stays zero-init to match Pi05.
261
+ """
262
+ src_layers = None
263
+ if hasattr(qwen2_lm, "model") and hasattr(qwen2_lm.model, "layers"):
264
+ src_layers = qwen2_lm.model.layers
265
+ elif hasattr(qwen2_lm, "layers"):
266
+ src_layers = qwen2_lm.layers
267
+ if src_layers is None:
268
+ raise ValueError("Unsupported qwen2_lm: cannot locate `.model.layers`.")
269
+
270
+ if len(src_layers) != len(self.layers):
271
+ raise ValueError(f"Layer count mismatch: {len(src_layers)=} vs {len(self.layers)=}")
272
+
273
+ for dst, src in zip(self.layers, src_layers, strict=True):
274
+ # attention
275
+ dst.self_attn.q_proj.load_state_dict(src.self_attn.q_proj.state_dict())
276
+ dst.self_attn.k_proj.load_state_dict(src.self_attn.k_proj.state_dict())
277
+ dst.self_attn.v_proj.load_state_dict(src.self_attn.v_proj.state_dict())
278
+ dst.self_attn.o_proj.load_state_dict(src.self_attn.o_proj.state_dict())
279
+ # mlp
280
+ dst.mlp.gate_proj.load_state_dict(src.mlp.gate_proj.state_dict())
281
+ dst.mlp.up_proj.load_state_dict(src.mlp.up_proj.state_dict())
282
+ dst.mlp.down_proj.load_state_dict(src.mlp.down_proj.state_dict())
283
+
284
+ def forward(
285
+ self,
286
+ action_tokens: torch.Tensor,
287
+ *,
288
+ prefix_kv_cache: list[tuple[torch.Tensor, torch.Tensor]],
289
+ prefix_key_mask: torch.Tensor,
290
+ position_ids: torch.Tensor,
291
+ adarms_cond: torch.Tensor,
292
+ suffix_key_mask: torch.Tensor | None = None,
293
+ ) -> torch.Tensor:
294
+ """
295
+ Args:
296
+ action_tokens: (B, S, D)
297
+ prefix_kv_cache: list[(k,v)] each (B, n_kv, P, hd) from InternVL prefix expert.
298
+ prefix_key_mask: (B, P) bool, True = valid prefix token.
299
+ position_ids: (B, S) positions for action tokens (prefix_len + [0..S-1]).
300
+ adarms_cond: (B, D) time conditioning vector.
301
+ suffix_key_mask: (B, S) bool, True = valid suffix token (optional; for padding).
302
+ """
303
+ if action_tokens.ndim != 3:
304
+ raise ValueError(f"action_tokens must be (B,S,D), got {tuple(action_tokens.shape)}")
305
+ bsz, s_len, _ = action_tokens.shape
306
+ if prefix_key_mask.ndim != 2 or int(prefix_key_mask.shape[0]) != bsz:
307
+ raise ValueError(f"prefix_key_mask must be (B,P), got {tuple(prefix_key_mask.shape)}")
308
+ if position_ids.shape != (bsz, s_len):
309
+ raise ValueError(f"position_ids must be (B,S)={bsz,s_len}, got {tuple(position_ids.shape)}")
310
+ if len(prefix_kv_cache) == 0:
311
+ raise ValueError("prefix_kv_cache is empty.")
312
+
313
+ # (cos,sin) for suffix tokens only (RoPE positions already baked into prefix cache).
314
+ position_embeddings = self.rotary_emb(action_tokens, position_ids)
315
+
316
+ if suffix_key_mask is None:
317
+ suffix_key_mask = torch.ones((bsz, s_len), device=action_tokens.device, dtype=torch.bool)
318
+ if suffix_key_mask.shape != (bsz, s_len):
319
+ raise ValueError(f"suffix_key_mask must be (B,S), got {tuple(suffix_key_mask.shape)}")
320
+
321
+ # Build Pi05 action-block attention mask: suffix queries attend to (valid prefix keys) + (valid suffix keys) fully.
322
+ prefix_part = (suffix_key_mask[:, None, :, None] & prefix_key_mask[:, None, None, :]) # (B,1,S,P)
323
+ suffix_part = (suffix_key_mask[:, None, :, None] & suffix_key_mask[:, None, None, :]) # (B,1,S,S)
324
+ allow = torch.cat([prefix_part, suffix_part], dim=-1) # (B,1,S,P+S)
325
+ attn_mask = torch.zeros(
326
+ (bsz, 1, s_len, int(prefix_key_mask.shape[1]) + s_len),
327
+ device=action_tokens.device,
328
+ dtype=action_tokens.dtype,
329
+ )
330
+ attn_mask = _masked_fill_min(attn_mask, allow)
331
+
332
+ x = action_tokens
333
+ for layer_idx, layer in enumerate(self.layers):
334
+ if layer_idx >= len(prefix_kv_cache):
335
+ raise ValueError(
336
+ "prefix_kv_cache has fewer layers than action expert. "
337
+ f"{len(prefix_kv_cache)=} < {len(self.layers)=}"
338
+ )
339
+ pk, pv = prefix_kv_cache[layer_idx]
340
+ x = layer(
341
+ x,
342
+ adarms_cond=adarms_cond,
343
+ position_embeddings=position_embeddings,
344
+ attention_mask=attn_mask,
345
+ prefix_k=pk,
346
+ prefix_v=pv,
347
+ )
348
+
349
+ x, _ = self.final_norm(x, adarms_cond)
350
+ return x
351
+
352
+
353
+ class Qwen3HeadRMSNorm(nn.Module):
354
+ """Qwen3-style RMSNorm used for `q_norm`/`k_norm` on per-head dim."""
355
+
356
+ def __init__(self, dim: int, *, eps: float = 1e-6):
357
+ super().__init__()
358
+ self.weight = nn.Parameter(torch.ones(dim))
359
+ self.eps = float(eps)
360
+
361
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
362
+ dtype = x.dtype
363
+ x_f32 = x.float()
364
+ var = x_f32.pow(2).mean(dim=-1, keepdim=True)
365
+ x_norm = x_f32 * torch.rsqrt(var + self.eps)
366
+ return (self.weight * x_norm).to(dtype=dtype)
367
+
368
+
369
+ class Qwen3PiSelfAttention(nn.Module):
370
+ """
371
+ Qwen3 attention variant for Pi05 action expert:
372
+ - queries from suffix tokens (action tokens)
373
+ - keys/values from concat(prefix_kv_cache, suffix_kv)
374
+ - uses full (non-causal) attention mask provided by caller.
375
+ """
376
+
377
+ def __init__(self, qwen_config: Any, layer_idx: int):
378
+ super().__init__()
379
+ try:
380
+ from transformers.models.qwen3.modeling_qwen3 import apply_rotary_pos_emb, repeat_kv
381
+ except Exception as e: # pragma: no cover
382
+ raise ImportError("transformers qwen3 internals are required for eo_pi_internvl.") from e
383
+
384
+ self._apply_rotary_pos_emb = apply_rotary_pos_emb
385
+ self._repeat_kv = repeat_kv
386
+
387
+ self.layer_idx = int(layer_idx)
388
+ self.hidden_size = int(qwen_config.hidden_size)
389
+ self.num_heads = int(qwen_config.num_attention_heads)
390
+ self.num_kv_heads = int(qwen_config.num_key_value_heads)
391
+ self.num_kv_groups = self.num_heads // self.num_kv_heads
392
+ self.head_dim = int(getattr(qwen_config, "head_dim", self.hidden_size // self.num_heads))
393
+
394
+ attn_bias = bool(getattr(qwen_config, "attention_bias", False))
395
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=attn_bias)
396
+ self.k_proj = nn.Linear(self.hidden_size, self.num_kv_heads * self.head_dim, bias=attn_bias)
397
+ self.v_proj = nn.Linear(self.hidden_size, self.num_kv_heads * self.head_dim, bias=attn_bias)
398
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=attn_bias)
399
+
400
+ eps = float(getattr(qwen_config, "rms_norm_eps", 1e-6))
401
+ self.q_norm = Qwen3HeadRMSNorm(self.head_dim, eps=eps)
402
+ self.k_norm = Qwen3HeadRMSNorm(self.head_dim, eps=eps)
403
+
404
+ def forward(
405
+ self,
406
+ hidden_states: torch.Tensor,
407
+ *,
408
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
409
+ attention_mask: torch.Tensor | None,
410
+ prefix_k: torch.Tensor,
411
+ prefix_v: torch.Tensor,
412
+ ) -> torch.Tensor:
413
+ bsz, seqlen, _ = hidden_states.shape
414
+ hidden_shape = (bsz, seqlen, -1, self.head_dim)
415
+
416
+ q = self.q_proj(hidden_states).view(hidden_shape)
417
+ k = self.k_proj(hidden_states).view(hidden_shape)
418
+ v = self.v_proj(hidden_states).view(hidden_shape)
419
+ q = self.q_norm(q).transpose(1, 2) # (B,n_heads,S,hd)
420
+ k = self.k_norm(k).transpose(1, 2) # (B,n_kv,S,hd)
421
+ v = v.transpose(1, 2) # (B,n_kv,S,hd)
422
+
423
+ cos, sin = position_embeddings
424
+ q, k = self._apply_rotary_pos_emb(q, k, cos, sin)
425
+
426
+ if prefix_k.ndim != 4 or prefix_v.ndim != 4:
427
+ raise ValueError(
428
+ f"prefix_k/v must be (B, n_kv, P, hd), got {tuple(prefix_k.shape)}, {tuple(prefix_v.shape)}"
429
+ )
430
+ if int(prefix_k.shape[0]) != bsz or int(prefix_v.shape[0]) != bsz:
431
+ raise ValueError("prefix_k/v batch mismatch.")
432
+ if int(prefix_k.shape[1]) != self.num_kv_heads or int(prefix_v.shape[1]) != self.num_kv_heads:
433
+ raise ValueError(
434
+ "prefix_k/v num_kv_heads mismatch: "
435
+ f"{int(prefix_k.shape[1])=} {int(prefix_v.shape[1])=} vs {self.num_kv_heads=}"
436
+ )
437
+ if int(prefix_k.shape[-1]) != self.head_dim or int(prefix_v.shape[-1]) != self.head_dim:
438
+ raise ValueError("prefix_k/v head_dim mismatch.")
439
+
440
+ k_all = torch.cat([prefix_k, k], dim=2) # (B, n_kv, P+S, hd)
441
+ v_all = torch.cat([prefix_v, v], dim=2)
442
+ k_all = self._repeat_kv(k_all, self.num_kv_groups) # (B, n_heads, P+S, hd)
443
+ v_all = self._repeat_kv(v_all, self.num_kv_groups)
444
+
445
+ if attention_mask is not None:
446
+ if attention_mask.ndim != 4:
447
+ raise ValueError(f"attention_mask must be 4D (B,1,S,K), got {tuple(attention_mask.shape)}")
448
+ attn_mask = attention_mask.expand(bsz, self.num_heads, seqlen, k_all.shape[-2])
449
+ else:
450
+ attn_mask = None
451
+
452
+ attn_out = torch.nn.functional.scaled_dot_product_attention(
453
+ q, k_all, v_all, attn_mask=attn_mask, dropout_p=0.0, is_causal=False
454
+ )
455
+ attn_out = attn_out.transpose(1, 2).contiguous().view(bsz, seqlen, self.num_heads * self.head_dim)
456
+ return self.o_proj(attn_out)
457
+
458
+
459
+ class Qwen3PiMLP(nn.Module):
460
+ def __init__(self, qwen_config: Any):
461
+ super().__init__()
462
+ hidden = int(qwen_config.hidden_size)
463
+ inter = int(qwen_config.intermediate_size)
464
+ self.gate_proj = nn.Linear(hidden, inter, bias=False)
465
+ self.up_proj = nn.Linear(hidden, inter, bias=False)
466
+ self.down_proj = nn.Linear(inter, hidden, bias=False)
467
+ act_name = str(getattr(qwen_config, "hidden_act", "silu"))
468
+ if act_name != "silu":
469
+ logger.warning_once("EO Pi action expert: forcing SiLU hidden_act for MLP (got %s).", act_name)
470
+ self.act = nn.SiLU()
471
+
472
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
473
+ return self.down_proj(self.act(self.gate_proj(x)) * self.up_proj(x))
474
+
475
+
476
+ class Qwen3PiDecoderLayer(nn.Module):
477
+ def __init__(self, qwen_config: Any, layer_idx: int):
478
+ super().__init__()
479
+ eps = float(getattr(qwen_config, "rms_norm_eps", 1e-6))
480
+ self.input_layernorm = AdaRMSNorm(int(qwen_config.hidden_size), eps=eps)
481
+ self.self_attn = Qwen3PiSelfAttention(qwen_config=qwen_config, layer_idx=layer_idx)
482
+ self.post_attention_layernorm = AdaRMSNorm(int(qwen_config.hidden_size), eps=eps)
483
+ self.mlp = Qwen3PiMLP(qwen_config=qwen_config)
484
+
485
+ def forward(
486
+ self,
487
+ hidden_states: torch.Tensor,
488
+ *,
489
+ adarms_cond: torch.Tensor,
490
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
491
+ attention_mask: torch.Tensor | None,
492
+ prefix_k: torch.Tensor,
493
+ prefix_v: torch.Tensor,
494
+ ) -> torch.Tensor:
495
+ residual = hidden_states
496
+ x, gate = self.input_layernorm(hidden_states, adarms_cond)
497
+ x = self.self_attn(
498
+ x,
499
+ position_embeddings=position_embeddings,
500
+ attention_mask=attention_mask,
501
+ prefix_k=prefix_k,
502
+ prefix_v=prefix_v,
503
+ )
504
+ hidden_states = residual + x * gate
505
+
506
+ residual = hidden_states
507
+ x, gate = self.post_attention_layernorm(hidden_states, adarms_cond)
508
+ x = self.mlp(x)
509
+ hidden_states = residual + x * gate
510
+ return hidden_states
511
+
512
+
513
+ class Qwen3PiActionExpert(nn.Module):
514
+ def __init__(self, qwen_config: Any, *, init_from_qwen3_lm: nn.Module | None = None):
515
+ super().__init__()
516
+ try:
517
+ from transformers.models.qwen3.modeling_qwen3 import Qwen3RotaryEmbedding
518
+ except Exception as e: # pragma: no cover
519
+ raise ImportError("transformers qwen3 internals are required for eo_pi_internvl.") from e
520
+
521
+ self.config = qwen_config
522
+ self.num_layers = int(qwen_config.num_hidden_layers)
523
+ self.layers = nn.ModuleList([Qwen3PiDecoderLayer(qwen_config, i) for i in range(self.num_layers)])
524
+ self.rotary_emb = Qwen3RotaryEmbedding(qwen_config)
525
+ self.final_norm = AdaRMSNorm(int(qwen_config.hidden_size), eps=float(getattr(qwen_config, "rms_norm_eps", 1e-6)))
526
+
527
+ if init_from_qwen3_lm is not None:
528
+ self._init_from_qwen3_lm(init_from_qwen3_lm)
529
+
530
+ def _init_from_qwen3_lm(self, qwen3_lm: nn.Module):
531
+ """
532
+ Copy attention/MLP weights from a Qwen3ForCausalLM (or Qwen3Model) into this expert.
533
+ AdaRMSNorm modulation stays zero-init to match Pi05.
534
+ """
535
+ src_layers = None
536
+ if hasattr(qwen3_lm, "model") and hasattr(qwen3_lm.model, "layers"):
537
+ src_layers = qwen3_lm.model.layers
538
+ elif hasattr(qwen3_lm, "layers"):
539
+ src_layers = qwen3_lm.layers
540
+ if src_layers is None:
541
+ raise ValueError("Unsupported qwen3_lm: cannot locate `.model.layers`.")
542
+
543
+ if len(src_layers) != len(self.layers):
544
+ raise ValueError(f"Layer count mismatch: {len(src_layers)=} vs {len(self.layers)=}")
545
+
546
+ for dst, src in zip(self.layers, src_layers, strict=True):
547
+ dst.self_attn.q_proj.load_state_dict(src.self_attn.q_proj.state_dict())
548
+ dst.self_attn.k_proj.load_state_dict(src.self_attn.k_proj.state_dict())
549
+ dst.self_attn.v_proj.load_state_dict(src.self_attn.v_proj.state_dict())
550
+ dst.self_attn.o_proj.load_state_dict(src.self_attn.o_proj.state_dict())
551
+ # head norms
552
+ if hasattr(src.self_attn, "q_norm") and hasattr(dst.self_attn, "q_norm"):
553
+ dst.self_attn.q_norm.weight.data.copy_(src.self_attn.q_norm.weight.data)
554
+ if hasattr(src.self_attn, "k_norm") and hasattr(dst.self_attn, "k_norm"):
555
+ dst.self_attn.k_norm.weight.data.copy_(src.self_attn.k_norm.weight.data)
556
+ # mlp
557
+ dst.mlp.gate_proj.load_state_dict(src.mlp.gate_proj.state_dict())
558
+ dst.mlp.up_proj.load_state_dict(src.mlp.up_proj.state_dict())
559
+ dst.mlp.down_proj.load_state_dict(src.mlp.down_proj.state_dict())
560
+
561
+ def forward(
562
+ self,
563
+ action_tokens: torch.Tensor,
564
+ *,
565
+ prefix_kv_cache: list[tuple[torch.Tensor, torch.Tensor]],
566
+ prefix_key_mask: torch.Tensor,
567
+ position_ids: torch.Tensor,
568
+ adarms_cond: torch.Tensor,
569
+ suffix_key_mask: torch.Tensor | None = None,
570
+ ) -> torch.Tensor:
571
+ if action_tokens.ndim != 3:
572
+ raise ValueError(f"action_tokens must be (B,S,D), got {tuple(action_tokens.shape)}")
573
+ bsz, s_len, _ = action_tokens.shape
574
+ if prefix_key_mask.ndim != 2 or int(prefix_key_mask.shape[0]) != bsz:
575
+ raise ValueError(f"prefix_key_mask must be (B,P), got {tuple(prefix_key_mask.shape)}")
576
+ if position_ids.shape != (bsz, s_len):
577
+ raise ValueError(f"position_ids must be (B,S)={bsz,s_len}, got {tuple(position_ids.shape)}")
578
+ if len(prefix_kv_cache) == 0:
579
+ raise ValueError("prefix_kv_cache is empty.")
580
+
581
+ position_embeddings = self.rotary_emb(action_tokens, position_ids)
582
+
583
+ if suffix_key_mask is None:
584
+ suffix_key_mask = torch.ones((bsz, s_len), device=action_tokens.device, dtype=torch.bool)
585
+ if suffix_key_mask.shape != (bsz, s_len):
586
+ raise ValueError(f"suffix_key_mask must be (B,S), got {tuple(suffix_key_mask.shape)}")
587
+
588
+ prefix_part = (suffix_key_mask[:, None, :, None] & prefix_key_mask[:, None, None, :]) # (B,1,S,P)
589
+ suffix_part = (suffix_key_mask[:, None, :, None] & suffix_key_mask[:, None, None, :]) # (B,1,S,S)
590
+ allow = torch.cat([prefix_part, suffix_part], dim=-1) # (B,1,S,P+S)
591
+ attn_mask = torch.zeros(
592
+ (bsz, 1, s_len, int(prefix_key_mask.shape[1]) + s_len),
593
+ device=action_tokens.device,
594
+ dtype=action_tokens.dtype,
595
+ )
596
+ attn_mask = _masked_fill_min(attn_mask, allow)
597
+
598
+ x = action_tokens
599
+ for layer_idx, layer in enumerate(self.layers):
600
+ if layer_idx >= len(prefix_kv_cache):
601
+ raise ValueError(
602
+ "prefix_kv_cache has fewer layers than action expert. "
603
+ f"{len(prefix_kv_cache)=} < {len(self.layers)=}"
604
+ )
605
+ pk, pv = prefix_kv_cache[layer_idx]
606
+ x = layer(
607
+ x,
608
+ adarms_cond=adarms_cond,
609
+ position_embeddings=position_embeddings,
610
+ attention_mask=attn_mask,
611
+ prefix_k=pk,
612
+ prefix_v=pv,
613
+ )
614
+
615
+ x, _ = self.final_norm(x, adarms_cond)
616
+ return x
617
+
618
+
619
+ @dataclass
620
+ class EO1InternVLPiFlowMatchingOutput(ModelOutput):
621
+ loss: torch.FloatTensor | None = None
622
+ fm_loss: torch.FloatTensor | None = None
623
+ fm_loss_pos: torch.FloatTensor | None = None
624
+ fm_loss_rot: torch.FloatTensor | None = None
625
+ fm_loss_gripper: torch.FloatTensor | None = None
626
+ ar_loss: torch.FloatTensor | None = None
627
+ actions: torch.FloatTensor | None = None
628
+
629
+ logits: torch.FloatTensor | None = None
630
+ hidden_states: tuple[torch.FloatTensor] | None = None
631
+ attentions: tuple[torch.FloatTensor] | None = None
632
+
633
+ def count_params(module, trainable_only=False):
634
+ ps = module.parameters()
635
+ if trainable_only:
636
+ ps = [p for p in ps if p.requires_grad]
637
+ return sum(p.numel() for p in ps)
638
+
639
+ class EO1InternVLPiFlowMatchingModel(PreTrainedModel):
640
+ """EO1 action model with InternVL prefix expert + Pi05-style (Qwen2/Qwen3) action expert (AdaRMSNorm timestep)."""
641
+
642
+ config_class = EO1InternVLPiFlowMatchingConfig
643
+ supports_gradient_checkpointing = True
644
+
645
+ def __init__(
646
+ self,
647
+ config: EO1InternVLPiFlowMatchingConfig,
648
+ internvl_backbone: nn.Module,
649
+ action_expert: nn.Module | None = None,
650
+ ):
651
+ super().__init__(config)
652
+ self.internvl_backbone = internvl_backbone
653
+
654
+ # InternVL uses a HF causal LM as `.language_model` (e.g. Qwen2ForCausalLM).
655
+ if not hasattr(self.internvl_backbone, "language_model"):
656
+ raise ValueError("internvl_backbone must have `.language_model`.")
657
+ # Do NOT register an alias module (e.g. `self.prefix_lm = self.internvl_backbone.language_model`).
658
+ # Registering both creates shared tensors under different state_dict keys, which safetensors refuses
659
+ # to save unless they are declared as tied weights. Use the property `prefix_lm` instead.
660
+
661
+ # ------------------------- Build action expert config (Pi05-style: smaller expert) -------------------------
662
+ prefix_cfg = self.prefix_lm.config
663
+ cfg_name = prefix_cfg.__class__.__name__
664
+
665
+ expert_cfg = copy.deepcopy(prefix_cfg)
666
+ if getattr(config, "expert_hidden_size", None) is not None:
667
+ expert_cfg.hidden_size = int(config.expert_hidden_size)
668
+ if getattr(config, "expert_intermediate_size", None) is not None:
669
+ expert_cfg.intermediate_size = int(config.expert_intermediate_size)
670
+ if getattr(config, "expert_num_attention_heads", None) is not None:
671
+ expert_cfg.num_attention_heads = int(config.expert_num_attention_heads)
672
+ if getattr(config, "expert_num_hidden_layers", None) is not None:
673
+ expert_cfg.num_hidden_layers = int(config.expert_num_hidden_layers)
674
+ # Keep head geometry aligned with prefix kv-cache.
675
+ if int(getattr(expert_cfg, "num_key_value_heads", -1)) != int(getattr(prefix_cfg, "num_key_value_heads", -2)):
676
+ raise ValueError(
677
+ "To reuse prefix KV-cache, expert and prefix must share num_key_value_heads. "
678
+ f"{int(getattr(prefix_cfg, 'num_key_value_heads'))=} vs {int(getattr(expert_cfg, 'num_key_value_heads'))=}."
679
+ )
680
+ if int(getattr(expert_cfg, "head_dim", -1)) != int(getattr(prefix_cfg, "head_dim", -2)):
681
+ raise ValueError(
682
+ "To reuse prefix KV-cache, expert and prefix must share head_dim. "
683
+ f"{int(getattr(prefix_cfg, 'head_dim'))=} vs {int(getattr(expert_cfg, 'head_dim'))=}."
684
+ )
685
+ if int(expert_cfg.num_attention_heads) % int(expert_cfg.num_key_value_heads) != 0:
686
+ raise ValueError(
687
+ "expert_num_attention_heads must be divisible by num_key_value_heads. "
688
+ f"{int(expert_cfg.num_attention_heads)=} {int(expert_cfg.num_key_value_heads)=}."
689
+ )
690
+ # Keep layer_types length consistent (Qwen3Config defines it).
691
+ if hasattr(expert_cfg, "layer_types") and isinstance(getattr(expert_cfg, "layer_types"), list):
692
+ if len(expert_cfg.layer_types) != int(expert_cfg.num_hidden_layers):
693
+ expert_cfg.layer_types = ["full_attention"] * int(expert_cfg.num_hidden_layers)
694
+
695
+ self._expert_hidden_size = int(expert_cfg.hidden_size)
696
+ self._expert_num_layers = int(expert_cfg.num_hidden_layers)
697
+ self._prefix_num_layers = int(getattr(prefix_cfg, "num_hidden_layers", self._expert_num_layers))
698
+
699
+ if self._expert_num_layers > self._prefix_num_layers:
700
+ raise ValueError(
701
+ "expert_num_hidden_layers cannot exceed prefix LM layers when using prefix KV-cache. "
702
+ f"{self._expert_num_layers=} > {self._prefix_num_layers=}."
703
+ )
704
+
705
+ mapping = str(getattr(config, "expert_layer_mapping", "last")).strip().lower()
706
+ if mapping == "last":
707
+ start = self._prefix_num_layers - self._expert_num_layers
708
+ self._prefix_kv_layer_indices = list(range(start, self._prefix_num_layers))
709
+ elif mapping == "first":
710
+ self._prefix_kv_layer_indices = list(range(self._expert_num_layers))
711
+ else:
712
+ raise ValueError(f"Unsupported expert_layer_mapping={mapping!r} (expected 'last' or 'first').")
713
+
714
+ max_action_dim = int(config.max_action_dim)
715
+
716
+ # Pi05: action embeddings do NOT concatenate timestep.
717
+ self.action_in_proj = nn.Linear(max_action_dim, self._expert_hidden_size)
718
+ self.action_out_proj = nn.Linear(self._expert_hidden_size, max_action_dim)
719
+
720
+ # Pi05: timestep is injected via AdaRMSNorm in the action expert.
721
+ self.time_mlp_in = nn.Linear(self._expert_hidden_size, self._expert_hidden_size)
722
+ self.time_mlp_out = nn.Linear(self._expert_hidden_size, self._expert_hidden_size)
723
+
724
+ if action_expert is not None:
725
+ self.action_expert = action_expert
726
+ else:
727
+ # Default: build an action expert (Qwen2/Qwen3) with its own (possibly smaller) config.
728
+ init_from = self.prefix_lm if bool(getattr(self.config, "expert_init_from_backbone", False)) else None
729
+ try:
730
+ if cfg_name == "Qwen2Config":
731
+ self.action_expert = Qwen2PiActionExpert(expert_cfg, init_from_qwen2_lm=init_from)
732
+ elif cfg_name == "Qwen3Config":
733
+ self.action_expert = Qwen3PiActionExpert(expert_cfg, init_from_qwen3_lm=init_from)
734
+ else:
735
+ raise NotImplementedError(
736
+ "eo_pi_internvl currently supports only Qwen2/Qwen3 LMs for action expert. "
737
+ f"Got: {cfg_name}"
738
+ )
739
+ except Exception as e:
740
+ raise RuntimeError(
741
+ "Failed to build/initialize action expert. If you set `expert_init_from_backbone=True`, "
742
+ "make sure expert_* hyperparams exactly match the prefix LM shapes, or set it to False "
743
+ "for Pi05-style random init."
744
+ ) from e
745
+
746
+ n_all = count_params(self.action_expert)
747
+ n_train = count_params(self.action_expert, trainable_only=True)
748
+ print(f"action_expert params: {n_all/1e6:.2f}M (trainable {n_train/1e6:.2f}M)")
749
+ self.post_init()
750
+
751
+ @property
752
+ def prefix_lm(self) -> nn.Module:
753
+ # A convenience accessor for the InternVL backbone LM used as the prefix model.
754
+ return self.internvl_backbone.language_model
755
+
756
+ @staticmethod
757
+ def _action_group_indices(action_dim: int, *, action_dim_mask: torch.Tensor | None = None) -> dict[str, list[int]]:
758
+ """
759
+ Best-effort split of action dims into position/rotation/gripper groups.
760
+
761
+ Supports both common layouts:
762
+ 1) Compact (single-arm): [xyz(3), rotvec(3), gripper(1)] -> 7 dims (or bimanual 14 dims).
763
+ 2) EO unified action encoding (see `dataset/action_encoding.py`):
764
+ left: 0:3 pos, 3:6 rotvec (or 3:9 r6d), 9 gripper
765
+ right: 10:13 pos, 13:16 rotvec (or 13:19 r6d), 19 gripper
766
+
767
+ Rotation repr is controlled via env var `EO_ACTION_ROT_REPR` (default rotvec).
768
+ """
769
+ d = int(action_dim)
770
+ if d <= 0:
771
+ return {"pos": [], "rot": [], "gripper": [], "other": []}
772
+
773
+ rot_repr = os.environ.get("EO_ACTION_ROT_REPR", "rotvec").strip().lower()
774
+ rot_is_r6d = rot_repr in ("r6d", "rot6d", "6d")
775
+
776
+ m_any = None
777
+ if action_dim_mask is not None and torch.is_tensor(action_dim_mask):
778
+ m = action_dim_mask.detach()
779
+ if m.ndim == 1:
780
+ m_any = m.to(torch.bool)
781
+ elif m.ndim == 2:
782
+ m_any = m.to(torch.bool).any(dim=0)
783
+ elif m.ndim == 3 and int(m.shape[1]) == 1:
784
+ m_any = m[:, 0, :].to(torch.bool).any(dim=0)
785
+ else:
786
+ m_any = m.reshape(-1, m.shape[-1]).to(torch.bool).any(dim=0)
787
+ if int(m_any.numel()) != d:
788
+ if int(m_any.numel()) > d:
789
+ m_any = m_any[:d]
790
+ else:
791
+ pad = torch.zeros((d - int(m_any.numel()),), dtype=torch.bool, device=m_any.device)
792
+ m_any = torch.cat([m_any, pad], dim=0)
793
+
794
+ # Infer effective dim span from mask if available (common when original action dim < max_action_dim).
795
+ eff = d
796
+ if m_any is not None and bool(m_any.any().item()):
797
+ eff = int(torch.nonzero(m_any, as_tuple=False).max().item()) + 1
798
+
799
+ pos: list[int] = []
800
+ rot: list[int] = []
801
+ gripper: list[int] = []
802
+
803
+ # Compact layout: 7D single-arm / 14D bimanual.
804
+ if eff in (7, 14):
805
+ arm_offsets = [0] if eff == 7 else [0, 7]
806
+ for off in arm_offsets:
807
+ pos.extend([off + i for i in range(0, 3) if off + i < d])
808
+ rot.extend([off + i for i in range(3, 6) if off + i < d])
809
+ g = off + 6
810
+ if g < d:
811
+ gripper.append(g)
812
+ used = set(pos) | set(rot) | set(gripper)
813
+ other = [i for i in range(d) if i not in used]
814
+ return {"pos": pos, "rot": rot, "gripper": gripper, "other": other}
815
+
816
+ # EO unified layout (10 dims per arm slot, supports bimanual at offset 10).
817
+ right_active = (d >= 20)
818
+ if m_any is not None and int(m_any.numel()) >= 20:
819
+ right_active = bool(m_any[10:20].any().item())
820
+
821
+ # Left arm.
822
+ pos.extend([i for i in range(0, min(3, d))])
823
+ rot.extend([i for i in range(3, min(6, d))])
824
+ if rot_is_r6d:
825
+ rot.extend([i for i in range(6, min(9, d))])
826
+ if 9 < d:
827
+ gripper.append(9)
828
+
829
+ # Right arm (offset 10) when active.
830
+ if right_active and d >= 20:
831
+ pos.extend([i for i in range(10, min(13, d))])
832
+ rot.extend([i for i in range(13, min(16, d))])
833
+ if rot_is_r6d:
834
+ rot.extend([i for i in range(16, min(19, d))])
835
+ if 19 < d:
836
+ gripper.append(19)
837
+
838
+ used = set(pos) | set(rot) | set(gripper)
839
+ other = [i for i in range(d) if i not in used]
840
+ return {"pos": pos, "rot": rot, "gripper": gripper, "other": other}
841
+
842
+ # ------------------------- EO1 Flow Matching utils -------------------------
843
+ def sample_noise(self, shape, device):
844
+ return torch.normal(mean=0.0, std=1.0, size=shape, dtype=torch.float32, device=device)
845
+
846
+ def sample_time(self, bsize, device):
847
+ beta_dist = torch.distributions.Beta(concentration1=1.5, concentration0=1.0)
848
+ time_beta = beta_dist.sample((bsize,)).to(device=device, dtype=torch.float32)
849
+ return time_beta * 0.999 + 0.001
850
+
851
+ def _embed_time_cond(self, timestep: torch.Tensor, *, dtype: torch.dtype, device: torch.device) -> torch.Tensor:
852
+ hidden = int(getattr(self, "_expert_hidden_size", self.prefix_lm.config.hidden_size))
853
+ t_emb = create_sinusoidal_pos_embedding(timestep, hidden, device=device).to(dtype=dtype)
854
+ t_emb = self.time_mlp_in(t_emb)
855
+ t_emb = F.silu(t_emb)
856
+ t_emb = self.time_mlp_out(t_emb)
857
+ t_emb = F.silu(t_emb)
858
+ return t_emb
859
+
860
+ def _select_prefix_kv_cache(self, prefix_kv_cache: list[tuple[torch.Tensor, torch.Tensor]]) -> list[tuple[torch.Tensor, torch.Tensor]]:
861
+ if not hasattr(self, "_prefix_kv_layer_indices"):
862
+ return prefix_kv_cache
863
+ idx = list(getattr(self, "_prefix_kv_layer_indices"))
864
+ if not idx:
865
+ return prefix_kv_cache
866
+ if max(idx) >= len(prefix_kv_cache):
867
+ raise ValueError(
868
+ "Prefix KV cache shorter than expected. "
869
+ f"{len(prefix_kv_cache)=} < {max(idx)+1=}."
870
+ )
871
+ return [prefix_kv_cache[i] for i in idx]
872
+
873
+ def _replace_img_context_embeddings(
874
+ self,
875
+ input_ids: torch.LongTensor,
876
+ inputs_embeds: torch.FloatTensor,
877
+ pixel_values: torch.FloatTensor,
878
+ image_flags: torch.LongTensor | None,
879
+ ) -> torch.FloatTensor:
880
+ img_context_token_id = self.config.img_context_token_id
881
+ if img_context_token_id is None:
882
+ raise ValueError("config.img_context_token_id is None (tokenizer/model not initialized).")
883
+
884
+ try:
885
+ vision_dtype = next(self.internvl_backbone.vision_model.parameters()).dtype
886
+ except Exception:
887
+ vision_dtype = inputs_embeds.dtype
888
+ pixel_values = pixel_values.to(device=inputs_embeds.device, dtype=vision_dtype)
889
+
890
+ vit_embeds = self.internvl_backbone.extract_feature(pixel_values) # (n_img, n_token, hidden)
891
+ if image_flags is not None:
892
+ image_flags = image_flags.squeeze(-1)
893
+ vit_embeds = vit_embeds[image_flags == 1]
894
+
895
+ bsz, _, hidden = inputs_embeds.shape
896
+ selected = input_ids == int(img_context_token_id) # (B,S)
897
+ n_ctx = int(selected.sum().item())
898
+ if n_ctx == 0:
899
+ return inputs_embeds
900
+
901
+ vit_flat = vit_embeds.reshape(-1, hidden)
902
+ if vit_flat.shape[0] < n_ctx:
903
+ raise ValueError(f"IMG_CONTEXT mismatch: need {n_ctx} embeddings, got {vit_flat.shape[0]}.")
904
+
905
+ mask3 = selected.unsqueeze(-1).expand_as(inputs_embeds)
906
+ src = vit_flat[:n_ctx].to(device=inputs_embeds.device, dtype=inputs_embeds.dtype).reshape(-1)
907
+ return inputs_embeds.masked_scatter(mask3, src)
908
+
909
+ @staticmethod
910
+ def _find_suffix_starts(action_mask_token: torch.Tensor, *, expected_horizon: int | None = None) -> torch.Tensor:
911
+ if action_mask_token.ndim != 2:
912
+ raise ValueError(f"action_mask_token must be (B,S), got {tuple(action_mask_token.shape)}")
913
+ bsz = int(action_mask_token.shape[0])
914
+ starts = torch.empty((bsz,), dtype=torch.long, device=action_mask_token.device)
915
+ for b in range(bsz):
916
+ pos = torch.nonzero(action_mask_token[b], as_tuple=False).squeeze(-1)
917
+ if int(pos.numel()) == 0:
918
+ raise ValueError(f"Expected at least 1 action token per sample, got 0 for batch {b}.")
919
+ if expected_horizon is not None and int(pos.numel()) not in (1, int(expected_horizon)):
920
+ raise ValueError(
921
+ f"Expected 1 or {int(expected_horizon)} action tokens per sample, got {int(pos.numel())} for batch {b}."
922
+ )
923
+ starts[b] = pos.min()
924
+ return starts
925
+
926
+ # ------------------------- Forward (train) -------------------------
927
+ def forward(
928
+ self,
929
+ input_ids: torch.LongTensor | None = None,
930
+ attention_mask: torch.Tensor | None = None,
931
+ position_ids: torch.LongTensor | None = None, # noqa: ARG002 - recomputed for pi05 mask
932
+ inputs_embeds: torch.FloatTensor | None = None, # noqa: ARG002 - use InternVL embeddings
933
+ labels: torch.LongTensor | None = None, # noqa: ARG002 - Pi05 does not train AR loss here
934
+ pixel_values: torch.FloatTensor | None = None,
935
+ image_flags: torch.LongTensor | None = None,
936
+ states: torch.Tensor | None = None, # noqa: ARG002 - Pi05: state should be discrete in text
937
+ actions: torch.Tensor | None = None,
938
+ action_is_pad: torch.Tensor | None = None,
939
+ action_dim_mask: torch.Tensor | None = None,
940
+ use_cache: bool | None = None, # noqa: ARG002
941
+ output_attentions: bool | None = None, # noqa: ARG002
942
+ output_hidden_states: bool | None = None, # noqa: ARG002
943
+ **kwargs,
944
+ ) -> EO1InternVLPiFlowMatchingOutput:
945
+ if input_ids is None:
946
+ raise ValueError("Pi model requires `input_ids`.")
947
+ if actions is None:
948
+ raise ValueError("Pi model forward requires `actions` (flow-matching).")
949
+ if attention_mask is None:
950
+ attention_mask = torch.ones_like(input_ids, dtype=torch.long, device=input_ids.device)
951
+
952
+ action_token_id = self.config.action_token_id
953
+ if action_token_id is None:
954
+ raise ValueError("config.action_token_id is None (tokenizer/model not initialized).")
955
+ action_pass_id = self.config.action_pass_id
956
+
957
+ noise_mask = input_ids == int(action_token_id)
958
+ pass_mask = (input_ids == int(action_pass_id)) if action_pass_id is not None else torch.zeros_like(noise_mask)
959
+ action_mask_token = noise_mask | pass_mask # (B, S)
960
+
961
+ bsz, horizon, act_dim = actions.shape
962
+
963
+ suffix_starts = self._find_suffix_starts(action_mask_token, expected_horizon=int(horizon)) # (B,)
964
+ prefix_len = int(suffix_starts.max().item())
965
+
966
+ # ---------------- Prefix expert (InternVL LM) ----------------
967
+ prefix_ids = input_ids[:, :prefix_len]
968
+ prefix_am = attention_mask[:, :prefix_len].to(dtype=torch.bool, device=input_ids.device)
969
+ ar = torch.arange(prefix_len, device=input_ids.device)
970
+ prefix_valid = prefix_am & (ar[None, :] < suffix_starts[:, None])
971
+
972
+ prefix_embeds = self.prefix_lm.get_input_embeddings()(prefix_ids).clone()
973
+ if pixel_values is not None:
974
+ prefix_embeds = self._replace_img_context_embeddings(
975
+ input_ids=prefix_ids,
976
+ inputs_embeds=prefix_embeds,
977
+ pixel_values=pixel_values,
978
+ image_flags=image_flags,
979
+ )
980
+
981
+ prefix_attn = prefix_valid.to(dtype=torch.long)
982
+ prefix_out = self.prefix_lm.model(
983
+ inputs_embeds=prefix_embeds,
984
+ attention_mask=prefix_attn,
985
+ use_cache=True,
986
+ return_dict=True,
987
+ )
988
+ prefix_pkv = prefix_out.past_key_values
989
+ prefix_kv_cache = [prefix_pkv[i] for i in range(len(prefix_pkv))]
990
+ prefix_kv_cache = self._select_prefix_kv_cache(prefix_kv_cache)
991
+
992
+ # ---------------- Flow Matching ----------------
993
+ actions_f32 = actions.to(dtype=torch.float32, device=input_ids.device)
994
+ time = self.sample_time(int(bsz), input_ids.device) # (B,)
995
+ noise = self.sample_noise(actions_f32.shape, input_ids.device)
996
+ time_expanded = time[:, None, None]
997
+ x_t = time_expanded * noise + (1 - time_expanded) * actions_f32
998
+ u_t = noise - actions_f32
999
+
1000
+ # Action tokens: no timestep concatenation in Pi05.
1001
+ action_tokens = self.action_in_proj(x_t.to(dtype=self.action_in_proj.weight.dtype)) # (B,H,D)
1002
+
1003
+ # AdaRMSNorm conditioning vector (Pi05).
1004
+ adarms_cond = self._embed_time_cond(time, dtype=action_tokens.dtype, device=action_tokens.device)
1005
+
1006
+ # Suffix RoPE positions follow the *per-sample* prefix length (suffix_starts).
1007
+ pos_ids = suffix_starts[:, None] + torch.arange(horizon, device=input_ids.device)[None, :]
1008
+
1009
+ suffix_valid = torch.ones((int(bsz), int(horizon)), device=input_ids.device, dtype=torch.bool)
1010
+ if action_is_pad is not None:
1011
+ suffix_valid = suffix_valid & (~action_is_pad.to(device=input_ids.device, dtype=torch.bool))
1012
+
1013
+ expert_h = self.action_expert(
1014
+ action_tokens,
1015
+ prefix_kv_cache=prefix_kv_cache,
1016
+ prefix_key_mask=prefix_valid,
1017
+ position_ids=pos_ids,
1018
+ adarms_cond=adarms_cond,
1019
+ suffix_key_mask=suffix_valid,
1020
+ )
1021
+ v_t = self.action_out_proj(expert_h).to(dtype=torch.float32) # (B,H,A)
1022
+
1023
+ # Loss: average over *valid elements* (step mask + action_dim_mask).
1024
+ target = u_t.to(dtype=v_t.dtype)
1025
+ per_elem = (v_t - target) ** 2 # (B,H,A)
1026
+
1027
+ valid = suffix_valid[:, :, None] if suffix_valid is not None else torch.ones((int(bsz), int(horizon), 1), device=per_elem.device, dtype=torch.bool)
1028
+ adm_for_groups = None
1029
+ if action_dim_mask is not None:
1030
+ adm = action_dim_mask
1031
+ if not torch.is_tensor(adm):
1032
+ adm = torch.as_tensor(adm)
1033
+ adm = adm.to(device=per_elem.device, dtype=torch.bool)
1034
+ if adm.ndim == 1:
1035
+ adm = adm.view(1, -1).expand(int(bsz), -1)
1036
+ elif adm.ndim == 2:
1037
+ pass
1038
+ elif adm.ndim == 3 and int(adm.shape[1]) == 1:
1039
+ adm = adm[:, 0, :]
1040
+ else:
1041
+ adm = adm.reshape(int(bsz), -1)
1042
+
1043
+ if int(adm.shape[-1]) == int(per_elem.shape[-1]):
1044
+ valid = valid & adm[:, None, :]
1045
+ adm_for_groups = adm
1046
+ else:
1047
+ logger.warning_once(
1048
+ "Ignoring action_dim_mask due to shape mismatch in PI FM loss: "
1049
+ f"{tuple(adm.shape)=} vs expected (B,{int(per_elem.shape[-1])})."
1050
+ )
1051
+
1052
+ # Exclude padding/unused action dims ("other") from FM loss.
1053
+ # We only train on {pos, rot, gripper} dims so `fm_loss` matches the meaningful action space.
1054
+ pos_mask = rot_mask = grip_mask = None
1055
+ try:
1056
+ a_dim = int(per_elem.shape[-1])
1057
+ pos_mask = torch.zeros((int(bsz), a_dim), device=per_elem.device, dtype=torch.bool)
1058
+ rot_mask = torch.zeros_like(pos_mask)
1059
+ grip_mask = torch.zeros_like(pos_mask)
1060
+ for bi in range(int(bsz)):
1061
+ g = self._action_group_indices(a_dim, action_dim_mask=(adm_for_groups[bi] if adm_for_groups is not None else None))
1062
+ if g["pos"]:
1063
+ pos_mask[bi, g["pos"]] = True
1064
+ if g["rot"]:
1065
+ rot_mask[bi, g["rot"]] = True
1066
+ if g["gripper"]:
1067
+ grip_mask[bi, g["gripper"]] = True
1068
+ group_mask = pos_mask | rot_mask | grip_mask # (B,A)
1069
+ empty = ~group_mask.any(dim=1)
1070
+ if empty.any():
1071
+ fallback = adm_for_groups if adm_for_groups is not None else torch.ones_like(group_mask)
1072
+ group_mask[empty] = fallback[empty]
1073
+ valid = valid & group_mask[:, None, :]
1074
+ except Exception:
1075
+ pos_mask = rot_mask = grip_mask = None
1076
+
1077
+ weight = valid.to(dtype=per_elem.dtype)
1078
+ denom = weight.sum().clamp_min(1)
1079
+ fm_loss = (per_elem * weight).sum() / denom
1080
+
1081
+ fm_loss_pos = None
1082
+ fm_loss_rot = None
1083
+ fm_loss_gripper = None
1084
+ # Decompose FM loss by action groups (auxiliary logs only; never crash training for these).
1085
+ try:
1086
+ if pos_mask is not None:
1087
+ pos_w = (weight * pos_mask[:, None, :].to(dtype=weight.dtype)).sum()
1088
+ if bool((pos_w > 0).item()):
1089
+ fm_loss_pos = (per_elem * weight * pos_mask[:, None, :].to(dtype=weight.dtype)).sum() / pos_w.clamp_min(1)
1090
+ if rot_mask is not None:
1091
+ rot_w = (weight * rot_mask[:, None, :].to(dtype=weight.dtype)).sum()
1092
+ if bool((rot_w > 0).item()):
1093
+ fm_loss_rot = (per_elem * weight * rot_mask[:, None, :].to(dtype=weight.dtype)).sum() / rot_w.clamp_min(1)
1094
+ if grip_mask is not None:
1095
+ grip_w = (weight * grip_mask[:, None, :].to(dtype=weight.dtype)).sum()
1096
+ if bool((grip_w > 0).item()):
1097
+ fm_loss_gripper = (per_elem * weight * grip_mask[:, None, :].to(dtype=weight.dtype)).sum() / grip_w.clamp_min(1)
1098
+ except Exception:
1099
+ fm_loss_pos = fm_loss_rot = fm_loss_gripper = None
1100
+
1101
+ return EO1InternVLPiFlowMatchingOutput(
1102
+ loss=fm_loss,
1103
+ fm_loss=fm_loss,
1104
+ fm_loss_pos=fm_loss_pos,
1105
+ fm_loss_rot=fm_loss_rot,
1106
+ fm_loss_gripper=fm_loss_gripper,
1107
+ ar_loss=None,
1108
+ actions=v_t,
1109
+ logits=None,
1110
+ hidden_states=None,
1111
+ attentions=None,
1112
+ )
1113
+
1114
+ @torch.no_grad()
1115
+ def sample_actions(
1116
+ self,
1117
+ input_ids: torch.LongTensor | None = None,
1118
+ attention_mask: torch.Tensor | None = None,
1119
+ position_ids: torch.LongTensor | None = None, # noqa: ARG002
1120
+ pixel_values: torch.FloatTensor | None = None,
1121
+ image_flags: torch.LongTensor | None = None,
1122
+ num_steps: int | None = None,
1123
+ noise: torch.Tensor | None = None,
1124
+ **kwargs,
1125
+ ) -> Tensor:
1126
+ if input_ids is None:
1127
+ raise ValueError("sample_actions requires input_ids.")
1128
+ if attention_mask is None:
1129
+ attention_mask = torch.ones_like(input_ids, dtype=torch.long, device=input_ids.device)
1130
+
1131
+ chunk_size = int(self.config.action_chunk_size)
1132
+ max_action_dim = int(self.config.max_action_dim)
1133
+ steps = int(num_steps) if num_steps is not None else int(self.config.num_denoise_steps)
1134
+ dt = torch.tensor(-1.0 / max(1, steps), device=input_ids.device, dtype=torch.float32)
1135
+
1136
+ action_token_id = self.config.action_token_id
1137
+ if action_token_id is None:
1138
+ raise ValueError("config.action_token_id is None (tokenizer/model not initialized).")
1139
+ action_pass_id = self.config.action_pass_id
1140
+
1141
+ noise_mask = input_ids == int(action_token_id)
1142
+ pass_mask = (input_ids == int(action_pass_id)) if action_pass_id is not None else torch.zeros_like(noise_mask)
1143
+ action_mask_token = noise_mask | pass_mask
1144
+
1145
+ bsz = int(input_ids.shape[0])
1146
+
1147
+ suffix_starts = self._find_suffix_starts(action_mask_token, expected_horizon=chunk_size)
1148
+ prefix_len = int(suffix_starts.max().item())
1149
+
1150
+ prefix_ids = input_ids[:, :prefix_len]
1151
+ prefix_am = attention_mask[:, :prefix_len].to(dtype=torch.bool, device=input_ids.device)
1152
+ ar = torch.arange(prefix_len, device=input_ids.device)
1153
+ prefix_valid = prefix_am & (ar[None, :] < suffix_starts[:, None])
1154
+
1155
+ prefix_embeds = self.prefix_lm.get_input_embeddings()(prefix_ids).clone()
1156
+ if pixel_values is not None:
1157
+ prefix_embeds = self._replace_img_context_embeddings(
1158
+ input_ids=prefix_ids,
1159
+ inputs_embeds=prefix_embeds,
1160
+ pixel_values=pixel_values,
1161
+ image_flags=image_flags,
1162
+ )
1163
+
1164
+ prefix_attn = prefix_valid.to(dtype=torch.long)
1165
+ prefix_out = self.prefix_lm.model(
1166
+ inputs_embeds=prefix_embeds,
1167
+ attention_mask=prefix_attn,
1168
+ use_cache=True,
1169
+ return_dict=True,
1170
+ )
1171
+ prefix_pkv = prefix_out.past_key_values
1172
+ prefix_kv_cache = [prefix_pkv[i] for i in range(len(prefix_pkv))]
1173
+ prefix_kv_cache = self._select_prefix_kv_cache(prefix_kv_cache)
1174
+
1175
+ device = input_ids.device
1176
+ if noise is None:
1177
+ x_t = self.sample_noise((bsz, chunk_size, max_action_dim), device=device).to(dtype=torch.float32)
1178
+ else:
1179
+ x_t = noise.to(device=device, dtype=torch.float32)
1180
+
1181
+ suffix_valid = torch.ones((bsz, chunk_size), device=device, dtype=torch.bool)
1182
+ pos_ids = suffix_starts[:, None] + torch.arange(chunk_size, device=device)[None, :]
1183
+
1184
+ for s in range(steps):
1185
+ t_scalar = 1.0 + float(s) * float(dt)
1186
+ time = torch.full((bsz,), t_scalar, device=device, dtype=torch.float32)
1187
+
1188
+ action_tokens = self.action_in_proj(x_t.to(dtype=self.action_in_proj.weight.dtype))
1189
+ adarms_cond = self._embed_time_cond(time, dtype=action_tokens.dtype, device=action_tokens.device)
1190
+
1191
+ expert_h = self.action_expert(
1192
+ action_tokens,
1193
+ prefix_kv_cache=prefix_kv_cache,
1194
+ prefix_key_mask=prefix_valid,
1195
+ position_ids=pos_ids,
1196
+ adarms_cond=adarms_cond,
1197
+ suffix_key_mask=suffix_valid,
1198
+ )
1199
+ v_t = self.action_out_proj(expert_h).to(dtype=torch.float32)
1200
+ x_t = x_t + dt * v_t
1201
+
1202
+ return x_t
1203
+
1204
+
1205
+ EO1InternVLPiFlowMatchingModel.register_for_auto_class()
checkpoint-50000/preprocessor_config.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoProcessor": "processing_eo1_internvl.EO1VisionProcessor"
4
+ },
5
+ "image_processor_type": "_InternVLImageProcessor",
6
+ "max_pixels": null,
7
+ "merge_size": 1,
8
+ "min_pixels": null,
9
+ "processor_class": "EO1VisionProcessor",
10
+ "temporal_patch_size": 1
11
+ }
checkpoint-50000/processing_eo1_internvl.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ EO1Vision processor for `eo_pi_internvl`.
3
+
4
+ This is the InternVL-backbone EO1 processor with a Pi05-style action prompt:
5
+ - We keep a *single* `<|action_pad|>` as a placeholder suffix token in text prompts.
6
+ - The action expert consumes *continuous* action tokens (length=`action_chunk_size`) internally, so we do not need to
7
+ repeat `<|action_pad|>` by chunk size in the text (this also keeps AR loss extensible).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from transformers.feature_extraction_utils import BatchFeature
13
+ from transformers.image_utils import ImageInput
14
+ from transformers.processing_utils import Unpack
15
+ from transformers.tokenization_utils_base import PreTokenizedInput, TextInput
16
+ from transformers.video_utils import VideoInput
17
+
18
+ from eo_internvl.model.processing_eo1_internvl import (
19
+ DEFAULT_ACTION_TOKEN,
20
+ EO1VisionProcessor as _BaseEO1VisionProcessor,
21
+ EO1VisionProcessorKwargs,
22
+ RobotInput,
23
+ )
24
+
25
+
26
+ class EO1VisionProcessor(_BaseEO1VisionProcessor):
27
+ def expand_action_prompt(self, chunk_size: int) -> str:
28
+ # Pi05-style: keep a single placeholder token in text; the model builds the full continuous action block.
29
+ return DEFAULT_ACTION_TOKEN
30
+
31
+ def __call__(
32
+ self,
33
+ images: ImageInput = None,
34
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
35
+ videos: VideoInput = None,
36
+ states: RobotInput = None,
37
+ actions: RobotInput = None,
38
+ **kwargs: Unpack[EO1VisionProcessorKwargs],
39
+ ) -> BatchFeature:
40
+ # Force action-token expansion length to 1 (no-op), regardless of robot_config / caller.
41
+ text_kwargs = kwargs.get("text_kwargs") or {}
42
+ text_kwargs = dict(text_kwargs)
43
+ text_kwargs["noise_token_num"] = 1
44
+ kwargs["text_kwargs"] = text_kwargs
45
+ return super().__call__(images=images, text=text, videos=videos, states=states, actions=actions, **kwargs)
46
+
47
+
48
+ EO1VisionProcessor.register_for_auto_class()
checkpoint-50000/processor_config.json ADDED
The diff for this file is too large to render. See raw diff
 
checkpoint-50000/scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3c1facdcf74036fdd5054c7c7673dfc059a3bca7b1cdefa5a2311c8a5fe867fd
3
+ size 1465
checkpoint-50000/special_tokens_map.json ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>",
16
+ "<img>",
17
+ "</img>",
18
+ "<IMG_CONTEXT>",
19
+ "<quad>",
20
+ "</quad>",
21
+ "<ref>",
22
+ "</ref>",
23
+ "<box>",
24
+ "</box>",
25
+ {
26
+ "content": "<|action_start|>",
27
+ "lstrip": false,
28
+ "normalized": false,
29
+ "rstrip": false,
30
+ "single_word": false
31
+ },
32
+ {
33
+ "content": "<|action_pad|>",
34
+ "lstrip": false,
35
+ "normalized": false,
36
+ "rstrip": false,
37
+ "single_word": false
38
+ },
39
+ {
40
+ "content": "<|action_end|>",
41
+ "lstrip": false,
42
+ "normalized": false,
43
+ "rstrip": false,
44
+ "single_word": false
45
+ },
46
+ {
47
+ "content": "<|action_pass|>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": false,
51
+ "single_word": false
52
+ },
53
+ {
54
+ "content": "<|state_start|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false
59
+ },
60
+ {
61
+ "content": "<|state_pad|>",
62
+ "lstrip": false,
63
+ "normalized": false,
64
+ "rstrip": false,
65
+ "single_word": false
66
+ },
67
+ {
68
+ "content": "<|state_end|>",
69
+ "lstrip": false,
70
+ "normalized": false,
71
+ "rstrip": false,
72
+ "single_word": false
73
+ },
74
+ {
75
+ "content": "<|vla|>",
76
+ "lstrip": false,
77
+ "normalized": false,
78
+ "rstrip": false,
79
+ "single_word": false
80
+ }
81
+ ],
82
+ "eos_token": {
83
+ "content": "<|im_end|>",
84
+ "lstrip": false,
85
+ "normalized": false,
86
+ "rstrip": false,
87
+ "single_word": false
88
+ },
89
+ "pad_token": {
90
+ "content": "<|endoftext|>",
91
+ "lstrip": false,
92
+ "normalized": false,
93
+ "rstrip": false,
94
+ "single_word": false
95
+ }
96
+ }
checkpoint-50000/tokenizer_config.json ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": false,
5
+ "added_tokens_decoder": {
6
+ "151643": {
7
+ "content": "<|endoftext|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "151644": {
15
+ "content": "<|im_start|>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "151645": {
23
+ "content": "<|im_end|>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ },
30
+ "151646": {
31
+ "content": "<|object_ref_start|>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ },
38
+ "151647": {
39
+ "content": "<|object_ref_end|>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": false,
43
+ "single_word": false,
44
+ "special": true
45
+ },
46
+ "151648": {
47
+ "content": "<|box_start|>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": false,
51
+ "single_word": false,
52
+ "special": true
53
+ },
54
+ "151649": {
55
+ "content": "<|box_end|>",
56
+ "lstrip": false,
57
+ "normalized": false,
58
+ "rstrip": false,
59
+ "single_word": false,
60
+ "special": true
61
+ },
62
+ "151650": {
63
+ "content": "<|quad_start|>",
64
+ "lstrip": false,
65
+ "normalized": false,
66
+ "rstrip": false,
67
+ "single_word": false,
68
+ "special": true
69
+ },
70
+ "151651": {
71
+ "content": "<|quad_end|>",
72
+ "lstrip": false,
73
+ "normalized": false,
74
+ "rstrip": false,
75
+ "single_word": false,
76
+ "special": true
77
+ },
78
+ "151652": {
79
+ "content": "<|vision_start|>",
80
+ "lstrip": false,
81
+ "normalized": false,
82
+ "rstrip": false,
83
+ "single_word": false,
84
+ "special": true
85
+ },
86
+ "151653": {
87
+ "content": "<|vision_end|>",
88
+ "lstrip": false,
89
+ "normalized": false,
90
+ "rstrip": false,
91
+ "single_word": false,
92
+ "special": true
93
+ },
94
+ "151654": {
95
+ "content": "<|vision_pad|>",
96
+ "lstrip": false,
97
+ "normalized": false,
98
+ "rstrip": false,
99
+ "single_word": false,
100
+ "special": true
101
+ },
102
+ "151655": {
103
+ "content": "<|image_pad|>",
104
+ "lstrip": false,
105
+ "normalized": false,
106
+ "rstrip": false,
107
+ "single_word": false,
108
+ "special": true
109
+ },
110
+ "151656": {
111
+ "content": "<|video_pad|>",
112
+ "lstrip": false,
113
+ "normalized": false,
114
+ "rstrip": false,
115
+ "single_word": false,
116
+ "special": true
117
+ },
118
+ "151657": {
119
+ "content": "<tool_call>",
120
+ "lstrip": false,
121
+ "normalized": false,
122
+ "rstrip": false,
123
+ "single_word": false,
124
+ "special": false
125
+ },
126
+ "151658": {
127
+ "content": "</tool_call>",
128
+ "lstrip": false,
129
+ "normalized": false,
130
+ "rstrip": false,
131
+ "single_word": false,
132
+ "special": false
133
+ },
134
+ "151659": {
135
+ "content": "<|fim_prefix|>",
136
+ "lstrip": false,
137
+ "normalized": false,
138
+ "rstrip": false,
139
+ "single_word": false,
140
+ "special": false
141
+ },
142
+ "151660": {
143
+ "content": "<|fim_middle|>",
144
+ "lstrip": false,
145
+ "normalized": false,
146
+ "rstrip": false,
147
+ "single_word": false,
148
+ "special": false
149
+ },
150
+ "151661": {
151
+ "content": "<|fim_suffix|>",
152
+ "lstrip": false,
153
+ "normalized": false,
154
+ "rstrip": false,
155
+ "single_word": false,
156
+ "special": false
157
+ },
158
+ "151662": {
159
+ "content": "<|fim_pad|>",
160
+ "lstrip": false,
161
+ "normalized": false,
162
+ "rstrip": false,
163
+ "single_word": false,
164
+ "special": false
165
+ },
166
+ "151663": {
167
+ "content": "<|repo_name|>",
168
+ "lstrip": false,
169
+ "normalized": false,
170
+ "rstrip": false,
171
+ "single_word": false,
172
+ "special": false
173
+ },
174
+ "151664": {
175
+ "content": "<|file_sep|>",
176
+ "lstrip": false,
177
+ "normalized": false,
178
+ "rstrip": false,
179
+ "single_word": false,
180
+ "special": false
181
+ },
182
+ "151665": {
183
+ "content": "<tool_response>",
184
+ "lstrip": false,
185
+ "normalized": false,
186
+ "rstrip": false,
187
+ "single_word": false,
188
+ "special": false
189
+ },
190
+ "151666": {
191
+ "content": "</tool_response>",
192
+ "lstrip": false,
193
+ "normalized": false,
194
+ "rstrip": false,
195
+ "single_word": false,
196
+ "special": false
197
+ },
198
+ "151667": {
199
+ "content": "<think>",
200
+ "lstrip": false,
201
+ "normalized": false,
202
+ "rstrip": false,
203
+ "single_word": false,
204
+ "special": false
205
+ },
206
+ "151668": {
207
+ "content": "</think>",
208
+ "lstrip": false,
209
+ "normalized": false,
210
+ "rstrip": false,
211
+ "single_word": false,
212
+ "special": false
213
+ },
214
+ "151669": {
215
+ "content": "<img>",
216
+ "lstrip": false,
217
+ "normalized": false,
218
+ "rstrip": false,
219
+ "single_word": false,
220
+ "special": true
221
+ },
222
+ "151670": {
223
+ "content": "</img>",
224
+ "lstrip": false,
225
+ "normalized": false,
226
+ "rstrip": false,
227
+ "single_word": false,
228
+ "special": true
229
+ },
230
+ "151671": {
231
+ "content": "<IMG_CONTEXT>",
232
+ "lstrip": false,
233
+ "normalized": false,
234
+ "rstrip": false,
235
+ "single_word": false,
236
+ "special": true
237
+ },
238
+ "151672": {
239
+ "content": "<quad>",
240
+ "lstrip": false,
241
+ "normalized": false,
242
+ "rstrip": false,
243
+ "single_word": false,
244
+ "special": true
245
+ },
246
+ "151673": {
247
+ "content": "</quad>",
248
+ "lstrip": false,
249
+ "normalized": false,
250
+ "rstrip": false,
251
+ "single_word": false,
252
+ "special": true
253
+ },
254
+ "151674": {
255
+ "content": "<ref>",
256
+ "lstrip": false,
257
+ "normalized": false,
258
+ "rstrip": false,
259
+ "single_word": false,
260
+ "special": true
261
+ },
262
+ "151675": {
263
+ "content": "</ref>",
264
+ "lstrip": false,
265
+ "normalized": false,
266
+ "rstrip": false,
267
+ "single_word": false,
268
+ "special": true
269
+ },
270
+ "151676": {
271
+ "content": "<box>",
272
+ "lstrip": false,
273
+ "normalized": false,
274
+ "rstrip": false,
275
+ "single_word": false,
276
+ "special": true
277
+ },
278
+ "151677": {
279
+ "content": "</box>",
280
+ "lstrip": false,
281
+ "normalized": false,
282
+ "rstrip": false,
283
+ "single_word": false,
284
+ "special": true
285
+ },
286
+ "151678": {
287
+ "content": "<|action_start|>",
288
+ "lstrip": false,
289
+ "normalized": false,
290
+ "rstrip": false,
291
+ "single_word": false,
292
+ "special": true
293
+ },
294
+ "151679": {
295
+ "content": "<|action_pad|>",
296
+ "lstrip": false,
297
+ "normalized": false,
298
+ "rstrip": false,
299
+ "single_word": false,
300
+ "special": true
301
+ },
302
+ "151680": {
303
+ "content": "<|action_end|>",
304
+ "lstrip": false,
305
+ "normalized": false,
306
+ "rstrip": false,
307
+ "single_word": false,
308
+ "special": true
309
+ },
310
+ "151681": {
311
+ "content": "<|action_pass|>",
312
+ "lstrip": false,
313
+ "normalized": false,
314
+ "rstrip": false,
315
+ "single_word": false,
316
+ "special": true
317
+ },
318
+ "151682": {
319
+ "content": "<|state_start|>",
320
+ "lstrip": false,
321
+ "normalized": false,
322
+ "rstrip": false,
323
+ "single_word": false,
324
+ "special": true
325
+ },
326
+ "151683": {
327
+ "content": "<|state_pad|>",
328
+ "lstrip": false,
329
+ "normalized": false,
330
+ "rstrip": false,
331
+ "single_word": false,
332
+ "special": true
333
+ },
334
+ "151684": {
335
+ "content": "<|state_end|>",
336
+ "lstrip": false,
337
+ "normalized": false,
338
+ "rstrip": false,
339
+ "single_word": false,
340
+ "special": true
341
+ },
342
+ "151685": {
343
+ "content": "<|vla|>",
344
+ "lstrip": false,
345
+ "normalized": false,
346
+ "rstrip": false,
347
+ "single_word": false,
348
+ "special": true
349
+ }
350
+ },
351
+ "additional_special_tokens": [
352
+ "<|im_start|>",
353
+ "<|im_end|>",
354
+ "<|object_ref_start|>",
355
+ "<|object_ref_end|>",
356
+ "<|box_start|>",
357
+ "<|box_end|>",
358
+ "<|quad_start|>",
359
+ "<|quad_end|>",
360
+ "<|vision_start|>",
361
+ "<|vision_end|>",
362
+ "<|vision_pad|>",
363
+ "<|image_pad|>",
364
+ "<|video_pad|>",
365
+ "<img>",
366
+ "</img>",
367
+ "<IMG_CONTEXT>",
368
+ "<quad>",
369
+ "</quad>",
370
+ "<ref>",
371
+ "</ref>",
372
+ "<box>",
373
+ "</box>",
374
+ "<|action_start|>",
375
+ "<|action_pad|>",
376
+ "<|action_end|>",
377
+ "<|action_pass|>",
378
+ "<|state_start|>",
379
+ "<|state_pad|>",
380
+ "<|state_end|>",
381
+ "<|vla|>"
382
+ ],
383
+ "auto_map": {
384
+ "AutoProcessor": "processing_eo1_internvl.EO1VisionProcessor"
385
+ },
386
+ "bos_token": null,
387
+ "clean_up_tokenization_spaces": false,
388
+ "eos_token": "<|im_end|>",
389
+ "errors": "replace",
390
+ "extra_special_tokens": {},
391
+ "model_max_length": 16384,
392
+ "pad_token": "<|endoftext|>",
393
+ "processor_class": "EO1VisionProcessor",
394
+ "split_special_tokens": false,
395
+ "tokenizer_class": "Qwen2Tokenizer",
396
+ "unk_token": null
397
+ }
checkpoint-50000/trainer_state.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:58f9f7743893701ba6cdf88873e9f18d813eca13e7ff03ddcbedf2a48e618f6c
3
+ size 21166190
checkpoint-50000/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2986750b87e7093da1db3130d9b43a750f3b374627b3398662dc9f725978b249
3
+ size 10001
checkpoint-50000/video_preprocessor_config.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoProcessor": "processing_eo1_internvl.EO1VisionProcessor"
4
+ },
5
+ "crop_size": null,
6
+ "data_format": "channels_first",
7
+ "default_to_square": true,
8
+ "device": null,
9
+ "do_center_crop": null,
10
+ "do_convert_rgb": null,
11
+ "do_normalize": null,
12
+ "do_pad": null,
13
+ "do_rescale": null,
14
+ "do_resize": null,
15
+ "do_sample_frames": null,
16
+ "fps": null,
17
+ "image_mean": null,
18
+ "image_std": null,
19
+ "input_data_format": null,
20
+ "merge_size": 1,
21
+ "num_frames": null,
22
+ "processor_class": "EO1VisionProcessor",
23
+ "resample": null,
24
+ "rescale_factor": 0.00392156862745098,
25
+ "return_metadata": false,
26
+ "size": null,
27
+ "size_divisor": null,
28
+ "temporal_patch_size": 1,
29
+ "video_metadata": null,
30
+ "video_processor_type": "_InternVLVideoProcessor"
31
+ }
checkpoint-50000/vocab.json ADDED
The diff for this file is too large to render. See raw diff