Upload folder using huggingface_hub
Browse files- .gitattributes +1 -0
- README.md +226 -0
- added_tokens.json +51 -0
- chat_template.jinja +81 -0
- config.json +67 -0
- configuration_step_vl.py +77 -0
- generation_config.json +10 -0
- model.safetensors +3 -0
- modeling_step_vl.py +557 -0
- processing_step3.py +464 -0
- processor_config.json +6 -0
- special_tokens_map.json +270 -0
- tokenizer.json +3 -0
- tokenizer_config.json +446 -0
- vision_encoder.py +451 -0
- vocab.json +0 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip 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
|
|
|
|
|
|
| 33 |
*.zip 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 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
This tiny model is intended for debugging. It is randomly initialized using the configuration adapted from [stepfun-ai/Step3-VL-10B](https://huggingface.co/stepfun-ai/Step3-VL-10B).
|
| 8 |
+
|
| 9 |
+
| File path | Size |
|
| 10 |
+
|------|------|
|
| 11 |
+
| model.safetensors | 6.0MB |
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
### Example usage:
|
| 15 |
+
|
| 16 |
+
- vLLM
|
| 17 |
+
|
| 18 |
+
```bash
|
| 19 |
+
vllm serve tiny-random/step3-vl \
|
| 20 |
+
--trust-remote-code \
|
| 21 |
+
--reasoning-parser deepseek_r1 \
|
| 22 |
+
--enable-auto-tool-choice \
|
| 23 |
+
--tool-call-parser hermes
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
- Transformers
|
| 27 |
+
|
| 28 |
+
```python
|
| 29 |
+
import torch
|
| 30 |
+
from transformers import AutoModelForCausalLM, AutoProcessor
|
| 31 |
+
|
| 32 |
+
model_id = "tiny-random/step3-vl"
|
| 33 |
+
messages = [
|
| 34 |
+
{
|
| 35 |
+
"role": "user",
|
| 36 |
+
"content": [
|
| 37 |
+
{
|
| 38 |
+
"type": "image",
|
| 39 |
+
"url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"
|
| 40 |
+
},
|
| 41 |
+
{
|
| 42 |
+
"type": "text",
|
| 43 |
+
"text": "describe this image"
|
| 44 |
+
}
|
| 45 |
+
],
|
| 46 |
+
}
|
| 47 |
+
]
|
| 48 |
+
processor = AutoProcessor.from_pretrained(
|
| 49 |
+
model_id,
|
| 50 |
+
trust_remote_code=True,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 54 |
+
model_id,
|
| 55 |
+
torch_dtype=torch.bfloat16,
|
| 56 |
+
device_map="cuda",
|
| 57 |
+
trust_remote_code=True,
|
| 58 |
+
key_mapping={
|
| 59 |
+
"^vision_model": "model.vision_model",
|
| 60 |
+
r"^model(?!\.(language_model|vision_model))": "model.language_model",
|
| 61 |
+
"vit_large_projector": "model.vit_large_projector",
|
| 62 |
+
}
|
| 63 |
+
)
|
| 64 |
+
inputs = processor.apply_chat_template(
|
| 65 |
+
messages,
|
| 66 |
+
tokenize=True,
|
| 67 |
+
add_generation_prompt=True,
|
| 68 |
+
return_dict=True,
|
| 69 |
+
return_tensors="pt"
|
| 70 |
+
).to(model.device)
|
| 71 |
+
inputs.pop("token_type_ids", None)
|
| 72 |
+
generated_ids = model.generate(**inputs, max_new_tokens=16)
|
| 73 |
+
output_text = processor.decode(
|
| 74 |
+
generated_ids[0][inputs["input_ids"].shape[1]:], skip_special_tokens=False)
|
| 75 |
+
print(output_text)
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
### Codes to create this repo:
|
| 79 |
+
|
| 80 |
+
<details>
|
| 81 |
+
<summary>Python codes</summary>
|
| 82 |
+
```python
|
| 83 |
+
import json
|
| 84 |
+
from pathlib import Path
|
| 85 |
+
|
| 86 |
+
import accelerate
|
| 87 |
+
import torch
|
| 88 |
+
from huggingface_hub import file_exists, hf_hub_download, list_repo_files
|
| 89 |
+
from safetensors.torch import save_file
|
| 90 |
+
from transformers import (
|
| 91 |
+
AutoConfig,
|
| 92 |
+
AutoModel,
|
| 93 |
+
AutoModelForCausalLM,
|
| 94 |
+
AutoProcessor,
|
| 95 |
+
AutoTokenizer,
|
| 96 |
+
GenerationConfig,
|
| 97 |
+
set_seed,
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
source_model_id = "stepfun-ai/Step3-VL-10B"
|
| 101 |
+
save_folder = "/tmp/tiny-random/step3-vl"
|
| 102 |
+
|
| 103 |
+
Path(save_folder).mkdir(parents=True, exist_ok=True)
|
| 104 |
+
for f in list_repo_files(source_model_id, repo_type="model"):
|
| 105 |
+
if (f.endswith('.json') or f.endswith('.py') or f.endswith('.model') or f.endswith('.jinja')) and (
|
| 106 |
+
not f.endswith('.index.json')
|
| 107 |
+
):
|
| 108 |
+
hf_hub_download(repo_id=source_model_id, filename=f,
|
| 109 |
+
repo_type="model", local_dir=save_folder)
|
| 110 |
+
|
| 111 |
+
def replace_file(filepath, old_string, new_string):
|
| 112 |
+
with open(filepath, 'r', encoding='utf-8') as f:
|
| 113 |
+
code = f.read()
|
| 114 |
+
code = code.replace(old_string, new_string)
|
| 115 |
+
with open(filepath, 'w', encoding='utf-8') as f:
|
| 116 |
+
f.write(code)
|
| 117 |
+
|
| 118 |
+
with open(f'{save_folder}/config.json') as f:
|
| 119 |
+
config_json = json.load(f)
|
| 120 |
+
|
| 121 |
+
config_json['text_config'].update({
|
| 122 |
+
'num_hidden_layers': 2,
|
| 123 |
+
'hidden_size': 8,
|
| 124 |
+
'head_dim': 32,
|
| 125 |
+
'intermediate_size': 64,
|
| 126 |
+
'num_attention_heads': 8,
|
| 127 |
+
"num_key_value_heads": 4,
|
| 128 |
+
'tie_word_embeddings': False,
|
| 129 |
+
})
|
| 130 |
+
config_json['vision_config'].update({
|
| 131 |
+
'width': 64,
|
| 132 |
+
'layers': 2,
|
| 133 |
+
'heads': 2,
|
| 134 |
+
})
|
| 135 |
+
with open(f"{save_folder}/config.json", "w", encoding='utf-8') as f:
|
| 136 |
+
json.dump(config_json, f, indent=2)
|
| 137 |
+
|
| 138 |
+
config = AutoConfig.from_pretrained(
|
| 139 |
+
save_folder,
|
| 140 |
+
trust_remote_code=True,
|
| 141 |
+
)
|
| 142 |
+
print(config)
|
| 143 |
+
torch.set_default_dtype(torch.bfloat16)
|
| 144 |
+
model = AutoModelForCausalLM.from_config(config, trust_remote_code=True)
|
| 145 |
+
torch.set_default_dtype(torch.float32)
|
| 146 |
+
# if file_exists(filename="generation_config.json", repo_id=source_model_id, repo_type='model'):
|
| 147 |
+
# model.generation_config = GenerationConfig.from_pretrained(
|
| 148 |
+
# source_model_id, trust_remote_code=True,
|
| 149 |
+
# )
|
| 150 |
+
set_seed(42)
|
| 151 |
+
model = model.cpu()
|
| 152 |
+
with torch.no_grad():
|
| 153 |
+
for name, p in sorted(model.named_parameters()):
|
| 154 |
+
torch.nn.init.normal_(p, 0, 0.1)
|
| 155 |
+
print(name, p.shape)
|
| 156 |
+
model_new = torch.nn.Identity()
|
| 157 |
+
model_new.model = model.model.language_model
|
| 158 |
+
model_new.vision_model = model.model.vision_model
|
| 159 |
+
model_new.lm_head = model.lm_head
|
| 160 |
+
model_new.vit_large_projector = model.model.vit_large_projector
|
| 161 |
+
state_dict = model_new.state_dict()
|
| 162 |
+
save_file(state_dict, f"{save_folder}/model.safetensors")
|
| 163 |
+
```
|
| 164 |
+
</details>
|
| 165 |
+
|
| 166 |
+
### Printing the model:
|
| 167 |
+
|
| 168 |
+
```text
|
| 169 |
+
Step3VL10BForCausalLM(
|
| 170 |
+
(model): StepRoboticsModel(
|
| 171 |
+
(vision_model): StepRoboticsVisionEncoder(
|
| 172 |
+
(conv1): Conv2d(3, 64, kernel_size=(14, 14), stride=(14, 14), bias=False)
|
| 173 |
+
(ln_pre): LayerNorm((64,), eps=1e-05, elementwise_affine=True)
|
| 174 |
+
(ln_post): Identity()
|
| 175 |
+
(transformer): EncoderVisionTransformer(
|
| 176 |
+
(resblocks): ModuleList(
|
| 177 |
+
(0-1): 2 x EncoderVisionBlock(
|
| 178 |
+
(attn): EncoderVisionAttention(
|
| 179 |
+
(out_proj): Linear(in_features=64, out_features=64, bias=True)
|
| 180 |
+
(rope): EncoderRope2D()
|
| 181 |
+
)
|
| 182 |
+
(ln_1): LayerNorm((64,), eps=1e-05, elementwise_affine=True)
|
| 183 |
+
(ln_2): LayerNorm((64,), eps=1e-05, elementwise_affine=True)
|
| 184 |
+
(mlp): EncoderMLP(
|
| 185 |
+
(c_fc): Linear(in_features=64, out_features=373, bias=True)
|
| 186 |
+
(act_fn): QuickGELUActivation()
|
| 187 |
+
(c_proj): Linear(in_features=373, out_features=64, bias=True)
|
| 188 |
+
)
|
| 189 |
+
(ls_1): EncoderLayerScale()
|
| 190 |
+
(ls_2): EncoderLayerScale()
|
| 191 |
+
)
|
| 192 |
+
)
|
| 193 |
+
)
|
| 194 |
+
(vit_downsampler1): Conv2d(64, 128, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))
|
| 195 |
+
(vit_downsampler2): Conv2d(128, 256, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))
|
| 196 |
+
)
|
| 197 |
+
(language_model): Qwen3Model(
|
| 198 |
+
(embed_tokens): Embedding(151936, 8)
|
| 199 |
+
(layers): ModuleList(
|
| 200 |
+
(0-1): 2 x Qwen3DecoderLayer(
|
| 201 |
+
(self_attn): Qwen3Attention(
|
| 202 |
+
(q_proj): Linear(in_features=8, out_features=256, bias=False)
|
| 203 |
+
(k_proj): Linear(in_features=8, out_features=128, bias=False)
|
| 204 |
+
(v_proj): Linear(in_features=8, out_features=128, bias=False)
|
| 205 |
+
(o_proj): Linear(in_features=256, out_features=8, bias=False)
|
| 206 |
+
(q_norm): Qwen3RMSNorm((32,), eps=1e-06)
|
| 207 |
+
(k_norm): Qwen3RMSNorm((32,), eps=1e-06)
|
| 208 |
+
)
|
| 209 |
+
(mlp): Qwen3MLP(
|
| 210 |
+
(gate_proj): Linear(in_features=8, out_features=64, bias=False)
|
| 211 |
+
(up_proj): Linear(in_features=8, out_features=64, bias=False)
|
| 212 |
+
(down_proj): Linear(in_features=64, out_features=8, bias=False)
|
| 213 |
+
(act_fn): SiLUActivation()
|
| 214 |
+
)
|
| 215 |
+
(input_layernorm): Qwen3RMSNorm((8,), eps=1e-06)
|
| 216 |
+
(post_attention_layernorm): Qwen3RMSNorm((8,), eps=1e-06)
|
| 217 |
+
)
|
| 218 |
+
)
|
| 219 |
+
(norm): Qwen3RMSNorm((8,), eps=1e-06)
|
| 220 |
+
(rotary_emb): Qwen3RotaryEmbedding()
|
| 221 |
+
)
|
| 222 |
+
(vit_large_projector): Linear(in_features=256, out_features=8, bias=False)
|
| 223 |
+
)
|
| 224 |
+
(lm_head): Linear(in_features=8, out_features=151936, bias=False)
|
| 225 |
+
)
|
| 226 |
+
```
|
added_tokens.json
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"</think>": 151668,
|
| 3 |
+
"</tool_call>": 151658,
|
| 4 |
+
"</tool_calls>": 151670,
|
| 5 |
+
"</tool_response>": 151666,
|
| 6 |
+
"<dream>": 151682,
|
| 7 |
+
"<dream_end>": 151684,
|
| 8 |
+
"<dream_start>": 151683,
|
| 9 |
+
"<im_end>": 151681,
|
| 10 |
+
"<im_patch>": 151679,
|
| 11 |
+
"<im_start>": 151680,
|
| 12 |
+
"<patch_end>": 151690,
|
| 13 |
+
"<patch_newline>": 151691,
|
| 14 |
+
"<patch_start>": 151689,
|
| 15 |
+
"<think>": 151667,
|
| 16 |
+
"<tool_call>": 151657,
|
| 17 |
+
"<tool_calls>": 151669,
|
| 18 |
+
"<tool_response>": 151665,
|
| 19 |
+
"<video_end>": 151688,
|
| 20 |
+
"<video_start>": 151687,
|
| 21 |
+
"<|BOT|>": 151672,
|
| 22 |
+
"<|CALL_END|>": 151674,
|
| 23 |
+
"<|CALL_START|>": 151673,
|
| 24 |
+
"<|EOT|>": 151671,
|
| 25 |
+
"<|IMG_END|>": 151678,
|
| 26 |
+
"<|IMG_START|>": 151677,
|
| 27 |
+
"<|MASK_1e69f|>": 151685,
|
| 28 |
+
"<|THINK_END|>": 151676,
|
| 29 |
+
"<|THINK_START|>": 151675,
|
| 30 |
+
"<|UNMASK_1e69f|>": 151686,
|
| 31 |
+
"<|box_end|>": 151649,
|
| 32 |
+
"<|box_start|>": 151648,
|
| 33 |
+
"<|endoftext|>": 151643,
|
| 34 |
+
"<|file_sep|>": 151664,
|
| 35 |
+
"<|fim_middle|>": 151660,
|
| 36 |
+
"<|fim_pad|>": 151662,
|
| 37 |
+
"<|fim_prefix|>": 151659,
|
| 38 |
+
"<|fim_suffix|>": 151661,
|
| 39 |
+
"<|im_end|>": 151645,
|
| 40 |
+
"<|im_start|>": 151644,
|
| 41 |
+
"<|image_pad|>": 151655,
|
| 42 |
+
"<|object_ref_end|>": 151647,
|
| 43 |
+
"<|object_ref_start|>": 151646,
|
| 44 |
+
"<|quad_end|>": 151651,
|
| 45 |
+
"<|quad_start|>": 151650,
|
| 46 |
+
"<|repo_name|>": 151663,
|
| 47 |
+
"<|video_pad|>": 151656,
|
| 48 |
+
"<|vision_end|>": 151653,
|
| 49 |
+
"<|vision_pad|>": 151654,
|
| 50 |
+
"<|vision_start|>": 151652
|
| 51 |
+
}
|
chat_template.jinja
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{% macro render_content(content) %}{% if content is none %}{{- '' }}{% elif content is string %}{{- content }}{% elif content is mapping %}{{- content['value'] if 'value' in content else content['text'] }}{% elif content is iterable %}{% for item in content %}{% if item.type == 'text' %}{{- item['value'] if 'value' in item else item['text'] }}{% elif item.type == 'image' %}<im_patch>{% endif %}{% endfor %}{% endif %}{% endmacro %}
|
| 2 |
+
{%- if tools %}
|
| 3 |
+
{{- '<|im_start|>system\n' }}
|
| 4 |
+
{%- if messages[0].role == 'system' %}
|
| 5 |
+
{{- render_content(messages[0].content) + '\n\n' }}
|
| 6 |
+
{%- endif %}
|
| 7 |
+
{{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
|
| 8 |
+
{%- for tool in tools %}
|
| 9 |
+
{{- "\n" }}
|
| 10 |
+
{{- tool | tojson }}
|
| 11 |
+
{%- endfor %}
|
| 12 |
+
{{- "\n</tools>\n\nAlways adhere to this exact format for tool use:\n<tool_calls>\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call>\n{additional_tool_calls}</tool_calls>\n\nNote:\n- For each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags.\n- `<function-name>` must be an exact match to one of the available tools.\n- `<args-json-object>` must be valid JSON that strictly follows the tool's parameters schema.<|im_end|>\n" }}
|
| 13 |
+
{%- else %}
|
| 14 |
+
{%- if messages[0].role == 'system' %}
|
| 15 |
+
{{- '<|im_start|>system\n' + render_content(messages[0].content) + '<|im_end|>\n' }}
|
| 16 |
+
{%- endif %}
|
| 17 |
+
{%- endif %}
|
| 18 |
+
{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
|
| 19 |
+
{%- for message in messages[::-1] %}
|
| 20 |
+
{%- set index = (messages|length - 1) - loop.index0 %}
|
| 21 |
+
{%- if ns.multi_step_tool and message.role == "user" and render_content(message.content) is string and not(render_content(message.content).startswith('<tool_response>') and render_content(message.content).endswith('</tool_response>')) %}
|
| 22 |
+
{%- set ns.multi_step_tool = false %}
|
| 23 |
+
{%- set ns.last_query_index = index %}
|
| 24 |
+
{%- endif %}
|
| 25 |
+
{%- endfor %}
|
| 26 |
+
{%- for message in messages %}
|
| 27 |
+
{%- set content = render_content(message.content) %}
|
| 28 |
+
{%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
|
| 29 |
+
{%- set role_name = 'observation' if (message.role == "system" and not loop.first and message.name == 'observation') else message.role %}
|
| 30 |
+
{{- '<|im_start|>' + role_name + '\n' + content + '<|im_end|>' + '\n' }}
|
| 31 |
+
{%- elif message.role == "assistant" %}
|
| 32 |
+
{%- if message.reasoning_content is string %}
|
| 33 |
+
{%- set reasoning_content = render_content(message.reasoning_content) %}
|
| 34 |
+
{%- else %}
|
| 35 |
+
{%- if '</think>' in content %}
|
| 36 |
+
{%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
|
| 37 |
+
{%- set content = content.split('</think>')[-1].lstrip('\n') %}
|
| 38 |
+
{%- else %}
|
| 39 |
+
{%- set reasoning_content = '' %}
|
| 40 |
+
{%- endif %}
|
| 41 |
+
{%- endif %}
|
| 42 |
+
{%- if loop.index0 > ns.last_query_index %}
|
| 43 |
+
{{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n' + content }}
|
| 44 |
+
{%- else %}
|
| 45 |
+
{{- '<|im_start|>' + message.role + '\n' + content }}
|
| 46 |
+
{%- endif %}
|
| 47 |
+
{%- if message.tool_calls %}
|
| 48 |
+
{{- '\n<tool_calls>' }}
|
| 49 |
+
{%- for tool_call in message.tool_calls %}
|
| 50 |
+
{{- '\n' }}
|
| 51 |
+
{%- if tool_call.function %}
|
| 52 |
+
{%- set tool_call = tool_call.function %}
|
| 53 |
+
{%- endif %}
|
| 54 |
+
{{- '<tool_call>\n{"name": "' }}
|
| 55 |
+
{{- tool_call.name }}
|
| 56 |
+
{{- '", "arguments": ' }}
|
| 57 |
+
{%- if tool_call.arguments is string %}
|
| 58 |
+
{{- tool_call.arguments }}
|
| 59 |
+
{%- else %}
|
| 60 |
+
{{- tool_call.arguments | tojson }}
|
| 61 |
+
{%- endif %}
|
| 62 |
+
{{- '}\n</tool_call>' }}
|
| 63 |
+
{%- endfor %}
|
| 64 |
+
{{- '\n</tool_calls>' }}
|
| 65 |
+
{%- endif %}
|
| 66 |
+
{{- '<|im_end|>\n' }}
|
| 67 |
+
{%- elif message.role == "tool" %}
|
| 68 |
+
{%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
|
| 69 |
+
{{- '<|im_start|>tool_response' }}
|
| 70 |
+
{%- endif %}
|
| 71 |
+
{{- '\n<tool_response>\n' }}
|
| 72 |
+
{{- content }}
|
| 73 |
+
{{- '\n</tool_response>' }}
|
| 74 |
+
{%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
|
| 75 |
+
{{- '<|im_end|>\n' }}
|
| 76 |
+
{%- endif %}
|
| 77 |
+
{%- endif %}
|
| 78 |
+
{%- endfor %}
|
| 79 |
+
{%- if add_generation_prompt %}
|
| 80 |
+
{{- '<|im_start|>assistant\n<think>\n' }}
|
| 81 |
+
{%- endif %}
|
config.json
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"StepVLForConditionalGeneration"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "configuration_step_vl.StepRoboticsConfig",
|
| 7 |
+
"AutoModelForCausalLM": "modeling_step_vl.Step3VL10BForCausalLM"
|
| 8 |
+
},
|
| 9 |
+
"model_type": "step_robotics",
|
| 10 |
+
"im_end_token": "<im_end>",
|
| 11 |
+
"im_patch_token": "<im_patch>",
|
| 12 |
+
"im_start_token": "<im_start>",
|
| 13 |
+
"image_token_len": 169,
|
| 14 |
+
"patch_token_len": 81,
|
| 15 |
+
"image_token_id": 151679,
|
| 16 |
+
"understand_projector_stride": 2,
|
| 17 |
+
"use_im_start_end": "true",
|
| 18 |
+
"vision_select_layer": -1,
|
| 19 |
+
"projector_bias": false,
|
| 20 |
+
"vision_config": {
|
| 21 |
+
"image_size": 728,
|
| 22 |
+
"patch_size": 14,
|
| 23 |
+
"width": 64,
|
| 24 |
+
"layers": 2,
|
| 25 |
+
"heads": 2,
|
| 26 |
+
"pool_type": "none",
|
| 27 |
+
"output_dim": null,
|
| 28 |
+
"use_cls_token": false,
|
| 29 |
+
"ls_init_value": 0.1,
|
| 30 |
+
"use_ln_post": false,
|
| 31 |
+
"hidden_act": "quick_gelu"
|
| 32 |
+
},
|
| 33 |
+
"text_config": {
|
| 34 |
+
"architectures": [
|
| 35 |
+
"Qwen3ForCausalLM"
|
| 36 |
+
],
|
| 37 |
+
"attention_bias": false,
|
| 38 |
+
"attention_dropout": 0.0,
|
| 39 |
+
"bos_token_id": 151643,
|
| 40 |
+
"eos_token_id": [
|
| 41 |
+
151643,
|
| 42 |
+
151645,
|
| 43 |
+
151679
|
| 44 |
+
],
|
| 45 |
+
"head_dim": 32,
|
| 46 |
+
"hidden_act": "silu",
|
| 47 |
+
"hidden_size": 8,
|
| 48 |
+
"initializer_range": 0.02,
|
| 49 |
+
"intermediate_size": 64,
|
| 50 |
+
"max_position_embeddings": 65536,
|
| 51 |
+
"max_window_layers": 36,
|
| 52 |
+
"model_type": "qwen3",
|
| 53 |
+
"num_attention_heads": 8,
|
| 54 |
+
"num_hidden_layers": 2,
|
| 55 |
+
"num_key_value_heads": 4,
|
| 56 |
+
"rms_norm_eps": 1e-06,
|
| 57 |
+
"rope_scaling": null,
|
| 58 |
+
"rope_theta": 1000000,
|
| 59 |
+
"sliding_window": null,
|
| 60 |
+
"tie_word_embeddings": false,
|
| 61 |
+
"torch_dtype": "bfloat16",
|
| 62 |
+
"transformers_version": "4.51.0",
|
| 63 |
+
"use_cache": true,
|
| 64 |
+
"use_sliding_window": false,
|
| 65 |
+
"vocab_size": 151936
|
| 66 |
+
}
|
| 67 |
+
}
|
configuration_step_vl.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Optional, Union
|
| 2 |
+
|
| 3 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 4 |
+
from transformers import Qwen3Config
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class StepRoboticsVisionEncoderConfig(PretrainedConfig):
|
| 8 |
+
|
| 9 |
+
def __init__(
|
| 10 |
+
self,
|
| 11 |
+
width=1536,
|
| 12 |
+
layers=47,
|
| 13 |
+
heads=16,
|
| 14 |
+
num_channels=3,
|
| 15 |
+
image_size=728,
|
| 16 |
+
mlp_ratio = 8960/1536,
|
| 17 |
+
patch_size=14,
|
| 18 |
+
hidden_act="quick_gelu",
|
| 19 |
+
layer_norm_eps=1e-5,
|
| 20 |
+
ues_cls_token=False,
|
| 21 |
+
use_ln_pre=True,
|
| 22 |
+
use_ln_post=False,
|
| 23 |
+
use_abs_posemb=True,
|
| 24 |
+
use_rope2d=True,
|
| 25 |
+
ls_init_value=0.1,
|
| 26 |
+
**kwargs,
|
| 27 |
+
):
|
| 28 |
+
self.width = width
|
| 29 |
+
self.layers = layers
|
| 30 |
+
self.heads = heads
|
| 31 |
+
self.num_channels = num_channels
|
| 32 |
+
self.patch_size = patch_size
|
| 33 |
+
self.image_size = image_size
|
| 34 |
+
self.mlp_ratio = mlp_ratio
|
| 35 |
+
self.layer_norm_eps = layer_norm_eps
|
| 36 |
+
self.hidden_act = hidden_act
|
| 37 |
+
self.ues_cls_token = ues_cls_token
|
| 38 |
+
self.use_ln_pre = use_ln_pre
|
| 39 |
+
self.ls_init_value = ls_init_value
|
| 40 |
+
self.use_ln_post = use_ln_post
|
| 41 |
+
self.use_abs_posemb = use_abs_posemb
|
| 42 |
+
self.use_rope2d = use_rope2d
|
| 43 |
+
super().__init__(**kwargs)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class StepRoboticsConfig(PretrainedConfig):
|
| 48 |
+
model_type = "step_robotics"
|
| 49 |
+
architectures = ["StepVLForConditionalGeneration"]
|
| 50 |
+
|
| 51 |
+
def __init__(
|
| 52 |
+
self,
|
| 53 |
+
vision_config: Optional[Union[dict, StepRoboticsVisionEncoderConfig]] = None,
|
| 54 |
+
text_config: Optional[Union[dict, Qwen3Config]] = None,
|
| 55 |
+
understand_projector_stride: int = 2,
|
| 56 |
+
projector_bias: bool = False,
|
| 57 |
+
image_token_id: int = 151679,
|
| 58 |
+
**kwargs,
|
| 59 |
+
) -> None:
|
| 60 |
+
if vision_config is None:
|
| 61 |
+
vision_config = StepRoboticsVisionEncoderConfig()
|
| 62 |
+
elif isinstance(vision_config, dict):
|
| 63 |
+
vision_config = StepRoboticsVisionEncoderConfig(**vision_config)
|
| 64 |
+
self.vision_config = vision_config
|
| 65 |
+
|
| 66 |
+
if text_config is None:
|
| 67 |
+
text_config = Qwen3Config()
|
| 68 |
+
elif isinstance(text_config, dict):
|
| 69 |
+
text_config = Qwen3Config(**text_config)
|
| 70 |
+
self.text_config = text_config
|
| 71 |
+
|
| 72 |
+
self.understand_projector_stride = understand_projector_stride
|
| 73 |
+
self.projector_bias = projector_bias
|
| 74 |
+
self.hidden_size = text_config.hidden_size
|
| 75 |
+
self.image_token_id = image_token_id
|
| 76 |
+
# Help Auto classes find the correct implementation when saving/loading.
|
| 77 |
+
super().__init__(**kwargs)
|
generation_config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"temperature": 1.0,
|
| 3 |
+
"top_p": 1.0,
|
| 4 |
+
"top_k": 0,
|
| 5 |
+
"eos_token_id": [
|
| 6 |
+
151643,
|
| 7 |
+
151645,
|
| 8 |
+
151679
|
| 9 |
+
]
|
| 10 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7046399a16ace116d6b79dfefc2ce0bf98df22619779ace933deacfe557d6d14
|
| 3 |
+
size 6324396
|
modeling_step_vl.py
ADDED
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The LLAMA4 and HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
from dataclasses import dataclass
|
| 16 |
+
from typing import Callable, Optional, Tuple, Union
|
| 17 |
+
from PIL import Image
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
import torch.nn as nn
|
| 21 |
+
import torch.nn.functional as F
|
| 22 |
+
from transformers import Qwen3Model
|
| 23 |
+
from transformers.cache_utils import Cache, DynamicCache
|
| 24 |
+
from transformers.generation import GenerationMixin
|
| 25 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, ModelOutput
|
| 26 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 27 |
+
from transformers.processing_utils import Unpack
|
| 28 |
+
from transformers.utils import TransformersKwargs, can_return_tuple, logging
|
| 29 |
+
|
| 30 |
+
from typing import Any, Literal, Optional, TypedDict, Union
|
| 31 |
+
|
| 32 |
+
from .configuration_step_vl import StepRoboticsConfig
|
| 33 |
+
from .vision_encoder import StepRoboticsVisionEncoder
|
| 34 |
+
logger = logging.get_logger(__name__)
|
| 35 |
+
|
| 36 |
+
class StepVLImagePixelInputs(TypedDict):
|
| 37 |
+
type: Literal["pixel_values"]
|
| 38 |
+
pixel_values: torch.Tensor
|
| 39 |
+
patch_pixel_values: Optional[torch.Tensor]
|
| 40 |
+
num_patches: list[int]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class StepVLImageEmbeddingInputs(TypedDict):
|
| 44 |
+
type: Literal["image_embeds"]
|
| 45 |
+
image_embeds: torch.Tensor
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
StepVLImageInputs = Union[StepVLImagePixelInputs,
|
| 49 |
+
StepVLImageEmbeddingInputs]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@dataclass
|
| 53 |
+
class StepVLCausalLMOutputWithPast(ModelOutput):
|
| 54 |
+
r"""
|
| 55 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 56 |
+
Language modeling loss (for next-token prediction).
|
| 57 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 58 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
| 59 |
+
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 60 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
| 61 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`)
|
| 62 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
|
| 63 |
+
`past_key_values` input) to speed up sequential decoding.
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
loss: Optional[torch.FloatTensor] = None
|
| 67 |
+
last_hidden_state: Optional[torch.FloatTensor] = None
|
| 68 |
+
logits: torch.FloatTensor = None
|
| 69 |
+
past_key_values: Optional[list[torch.FloatTensor]] = None
|
| 70 |
+
hidden_states: Optional[tuple[torch.FloatTensor]] = None
|
| 71 |
+
attentions: Optional[tuple[torch.FloatTensor]] = None
|
| 72 |
+
image_hidden_states: Optional[torch.FloatTensor] = None
|
| 73 |
+
|
| 74 |
+
def _flatten_embeddings(embeddings) -> torch.Tensor:
|
| 75 |
+
"""
|
| 76 |
+
Recursively flattens and concatenates NestedTensors on all but the last
|
| 77 |
+
dimension.
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
if isinstance(embeddings, torch.Tensor):
|
| 81 |
+
# Flatten all but the last dimension.
|
| 82 |
+
return embeddings.flatten(0, -2)
|
| 83 |
+
|
| 84 |
+
return torch.cat(tuple(_flatten_embeddings(t) for t in embeddings))
|
| 85 |
+
|
| 86 |
+
def _embedding_count_expression(embeddings) -> str:
|
| 87 |
+
"""
|
| 88 |
+
Constructs a debugging representation of the number of embeddings in the
|
| 89 |
+
NestedTensors.
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
if isinstance(embeddings, torch.Tensor):
|
| 93 |
+
return " x ".join([str(dim) for dim in embeddings.shape[:-1]])
|
| 94 |
+
|
| 95 |
+
return " + ".join(
|
| 96 |
+
_embedding_count_expression(inner) for inner in embeddings)
|
| 97 |
+
|
| 98 |
+
def _merge_multimodal_embeddings(
|
| 99 |
+
inputs_embeds: torch.Tensor,
|
| 100 |
+
is_multimodal: torch.Tensor,
|
| 101 |
+
multimodal_embeddings,
|
| 102 |
+
) -> torch.Tensor:
|
| 103 |
+
"""
|
| 104 |
+
Merge ``multimodal_embeddings`` into ``inputs_embeds`` by overwriting the
|
| 105 |
+
positions in ``inputs_embeds`` corresponding to placeholder tokens in
|
| 106 |
+
``input_ids``.
|
| 107 |
+
Note:
|
| 108 |
+
This updates ``inputs_embeds`` in place.
|
| 109 |
+
"""
|
| 110 |
+
num_expected_tokens = is_multimodal.sum().item()
|
| 111 |
+
assert isinstance(num_expected_tokens, int)
|
| 112 |
+
|
| 113 |
+
flattened = _flatten_embeddings(multimodal_embeddings)
|
| 114 |
+
if flattened.shape[0] != num_expected_tokens:
|
| 115 |
+
expr = _embedding_count_expression(multimodal_embeddings)
|
| 116 |
+
raise ValueError(
|
| 117 |
+
f"Attempted to assign {expr} = {flattened.shape[0]} "
|
| 118 |
+
f"multimodal tokens to {num_expected_tokens} placeholders")
|
| 119 |
+
|
| 120 |
+
is_multimodal = is_multimodal.to(inputs_embeds.device)
|
| 121 |
+
flattened = flattened.to(inputs_embeds.device)
|
| 122 |
+
inputs_embeds[is_multimodal] = flattened
|
| 123 |
+
return inputs_embeds
|
| 124 |
+
|
| 125 |
+
def merge_multimodal_embeddings(
|
| 126 |
+
input_ids: torch.Tensor,
|
| 127 |
+
inputs_embeds: torch.Tensor,
|
| 128 |
+
multimodal_embeddings,
|
| 129 |
+
placeholder_token_id: Union[int, list[int]],
|
| 130 |
+
) -> torch.Tensor:
|
| 131 |
+
"""
|
| 132 |
+
Merge ``multimodal_embeddings`` into ``inputs_embeds`` by overwriting the
|
| 133 |
+
positions in ``inputs_embeds`` corresponding to placeholder tokens in
|
| 134 |
+
``input_ids``.
|
| 135 |
+
|
| 136 |
+
``placeholder_token_id`` can be a list of token ids (e.g, token ids
|
| 137 |
+
of img_start, img_break, and img_end tokens) when needed: This means
|
| 138 |
+
the order of these tokens in the ``input_ids`` MUST MATCH the order of
|
| 139 |
+
their embeddings in ``multimodal_embeddings`` since we need to
|
| 140 |
+
slice-merge instead of individually scattering.
|
| 141 |
+
For example, if input_ids is "TTTTTSIIIBIIIBIIIETTT", where
|
| 142 |
+
- T is text token
|
| 143 |
+
- S is image start token
|
| 144 |
+
- I is image embedding token
|
| 145 |
+
- B is image break token
|
| 146 |
+
- E is image end token.
|
| 147 |
+
|
| 148 |
+
Then the image embeddings (that correspond to I's) from vision encoder
|
| 149 |
+
must be padded with embeddings of S, B, and E in the same order of
|
| 150 |
+
input_ids for a correct embedding merge.
|
| 151 |
+
Note:
|
| 152 |
+
This updates ``inputs_embeds`` in place.
|
| 153 |
+
"""
|
| 154 |
+
if isinstance(placeholder_token_id, list):
|
| 155 |
+
placeholder_token_id = torch.tensor(placeholder_token_id,
|
| 156 |
+
device=input_ids.device)
|
| 157 |
+
return _merge_multimodal_embeddings(
|
| 158 |
+
inputs_embeds,
|
| 159 |
+
torch.isin(input_ids, placeholder_token_id),
|
| 160 |
+
multimodal_embeddings,
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
return _merge_multimodal_embeddings(
|
| 164 |
+
inputs_embeds,
|
| 165 |
+
(input_ids == placeholder_token_id),
|
| 166 |
+
multimodal_embeddings,
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
class StepRoboticsPreTrainedModel(PreTrainedModel):
|
| 170 |
+
# Link this model family to its configuration class so PreTrainedModel.from_pretrained
|
| 171 |
+
# can load the config instead of failing with a NoneType error.
|
| 172 |
+
config_class = StepRoboticsConfig
|
| 173 |
+
supports_gradient_checkpointing = True
|
| 174 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 175 |
+
_supports_flash_attn = False
|
| 176 |
+
_supports_sdpa = True
|
| 177 |
+
_supports_flex_attn = True
|
| 178 |
+
_supports_static_cache = True
|
| 179 |
+
_supports_attention_backend = True
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
class StepRoboticsModel(StepRoboticsPreTrainedModel, GenerationMixin):
|
| 183 |
+
config: StepRoboticsConfig
|
| 184 |
+
base_model_prefix = ""
|
| 185 |
+
def __init__(self, config: StepRoboticsConfig):
|
| 186 |
+
super().__init__(config)
|
| 187 |
+
self.vision_model = StepRoboticsVisionEncoder(config.vision_config)
|
| 188 |
+
self.language_model = Qwen3Model(config.text_config)
|
| 189 |
+
self.vocab_size = config.text_config.vocab_size
|
| 190 |
+
self.vit_large_projector = nn.Linear(
|
| 191 |
+
config.vision_config.width * 4,
|
| 192 |
+
config.text_config.hidden_size,
|
| 193 |
+
bias=config.projector_bias)
|
| 194 |
+
self.image_placeholder_token_id = config.image_token_id
|
| 195 |
+
|
| 196 |
+
# Initialize weights and apply final processing
|
| 197 |
+
self.post_init()
|
| 198 |
+
|
| 199 |
+
def get_input_embeddings(
|
| 200 |
+
self,
|
| 201 |
+
input_ids: torch.Tensor,
|
| 202 |
+
multimodal_embeddings = None,
|
| 203 |
+
) -> torch.Tensor:
|
| 204 |
+
input_ids = input_ids.squeeze(0)
|
| 205 |
+
if multimodal_embeddings is None:
|
| 206 |
+
inputs_embeds = self.language_model.embed_tokens(input_ids)
|
| 207 |
+
else:
|
| 208 |
+
is_text = input_ids != self.config.image_token_id
|
| 209 |
+
text_ids = input_ids[is_text]
|
| 210 |
+
text_embeds = self.language_model.embed_tokens(text_ids)
|
| 211 |
+
|
| 212 |
+
inputs_embeds = torch.empty(input_ids.shape[0],
|
| 213 |
+
text_embeds.shape[-1],
|
| 214 |
+
dtype=text_embeds.dtype,
|
| 215 |
+
device=text_embeds.device)
|
| 216 |
+
inputs_embeds[is_text] = text_embeds
|
| 217 |
+
inputs_embeds = merge_multimodal_embeddings(
|
| 218 |
+
input_ids, inputs_embeds, multimodal_embeddings,
|
| 219 |
+
self.config.image_token_id)
|
| 220 |
+
inputs_embeds = inputs_embeds.unsqueeze(0)
|
| 221 |
+
return inputs_embeds
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def set_input_embeddings(self, value):
|
| 225 |
+
return self.language_model.set_input_embeddings(value)
|
| 226 |
+
|
| 227 |
+
def set_decoder(self, decoder):
|
| 228 |
+
self.language_model = decoder
|
| 229 |
+
|
| 230 |
+
def get_decoder(self):
|
| 231 |
+
return self.language_model
|
| 232 |
+
|
| 233 |
+
def _parse_and_validate_image_input(
|
| 234 |
+
self, **kwargs: object) -> Optional[StepVLImageInputs]:
|
| 235 |
+
pixel_values = kwargs.pop("pixel_values", None)
|
| 236 |
+
patch_pixel_values = kwargs.pop("patch_pixel_values", None)
|
| 237 |
+
num_patches = kwargs.pop("num_patches", None)
|
| 238 |
+
image_embeds = kwargs.pop("image_embeds", None)
|
| 239 |
+
|
| 240 |
+
if pixel_values is None and image_embeds is None:
|
| 241 |
+
return None
|
| 242 |
+
|
| 243 |
+
if pixel_values is not None:
|
| 244 |
+
# pixel_values = flatten_bn(pixel_values, concat=True)
|
| 245 |
+
if pixel_values.dim() >= 3:
|
| 246 |
+
pixel_values = pixel_values.view(-1, *pixel_values.shape[-3:])
|
| 247 |
+
if patch_pixel_values is not None:
|
| 248 |
+
# patch_pixel_values = flatten_bn(patch_pixel_values,
|
| 249 |
+
# concat=True)
|
| 250 |
+
patch_pixel_values = patch_pixel_values.view(
|
| 251 |
+
-1, *patch_pixel_values.shape[-3:])
|
| 252 |
+
# Handle empty patch_pixel_values by setting to None
|
| 253 |
+
if patch_pixel_values.shape[0] == 0:
|
| 254 |
+
patch_pixel_values = None
|
| 255 |
+
|
| 256 |
+
return StepVLImagePixelInputs(
|
| 257 |
+
type="pixel_values",
|
| 258 |
+
pixel_values=pixel_values.to(self.dtype).to(self.device),
|
| 259 |
+
patch_pixel_values=patch_pixel_values.to(self.dtype).to(
|
| 260 |
+
self.device) if patch_pixel_values is not None else None,
|
| 261 |
+
num_patches=num_patches,
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
if image_embeds is not None:
|
| 265 |
+
if image_embeds.dim() == 2 or image_embeds.dim() >= 3:
|
| 266 |
+
image_embeds = image_embeds.view(-1, image_embeds.shape[-1])
|
| 267 |
+
else:
|
| 268 |
+
raise ValueError(
|
| 269 |
+
f"Unexpected shape for image_embeds: {image_embeds.shape}")
|
| 270 |
+
|
| 271 |
+
return StepVLImageEmbeddingInputs(
|
| 272 |
+
type="image_embeds",
|
| 273 |
+
image_embeds=image_embeds.to(self.dtype).to(self.device),
|
| 274 |
+
)
|
| 275 |
+
return None
|
| 276 |
+
|
| 277 |
+
def _process_image_features(self,
|
| 278 |
+
image_features: torch.Tensor) -> torch.Tensor:
|
| 279 |
+
B, P = image_features.shape[:2]
|
| 280 |
+
HW = int(P ** 0.5)
|
| 281 |
+
image_features = image_features.permute(0, 2, 1).view(B, -1, HW, HW)
|
| 282 |
+
image_features = self.vision_model.vit_downsampler1(image_features)
|
| 283 |
+
image_features = self.vision_model.vit_downsampler2(image_features)
|
| 284 |
+
|
| 285 |
+
B, C, HW, HW = image_features.shape
|
| 286 |
+
image_features = image_features.view(B, -1, HW * HW).permute(0, 2, 1)
|
| 287 |
+
image_features = self.vit_large_projector(image_features)
|
| 288 |
+
return image_features
|
| 289 |
+
|
| 290 |
+
def _get_vision_model_output(self,
|
| 291 |
+
input_tensor: torch.Tensor) -> torch.Tensor:
|
| 292 |
+
return self.vision_model(input_tensor)
|
| 293 |
+
|
| 294 |
+
def _process_image_input(
|
| 295 |
+
self, image_input: StepVLImageInputs) -> tuple[torch.Tensor, ...]:
|
| 296 |
+
|
| 297 |
+
if image_input["type"] == "image_embeds":
|
| 298 |
+
image_features = image_input["image_embeds"]
|
| 299 |
+
else:
|
| 300 |
+
image_features = self._get_vision_model_output(
|
| 301 |
+
image_input["pixel_values"])
|
| 302 |
+
patch_image_features = self._get_vision_model_output(
|
| 303 |
+
image_input["patch_pixel_values"]
|
| 304 |
+
) if image_input["patch_pixel_values"] is not None else None
|
| 305 |
+
num_patches = image_input["num_patches"]
|
| 306 |
+
|
| 307 |
+
image_features = self._process_image_features(image_features)
|
| 308 |
+
patch_image_features = self._process_image_features(
|
| 309 |
+
patch_image_features) if patch_image_features is not None else None
|
| 310 |
+
|
| 311 |
+
merged_image_features = []
|
| 312 |
+
cur_patch_idx = 0
|
| 313 |
+
for i, num_patch in enumerate(num_patches):
|
| 314 |
+
cur_feature = []
|
| 315 |
+
if num_patch > 0:
|
| 316 |
+
patch_slice = patch_image_features[
|
| 317 |
+
cur_patch_idx:cur_patch_idx + num_patch]
|
| 318 |
+
cur_feature.append(patch_slice.view(-1, patch_slice.shape[-1]))
|
| 319 |
+
cur_feature.append(image_features[i].view(
|
| 320 |
+
-1, image_features.shape[-1]))
|
| 321 |
+
cur_patch_idx += num_patch
|
| 322 |
+
merged_image_features.append(
|
| 323 |
+
torch.cat(cur_feature) if len(cur_feature) >
|
| 324 |
+
1 else cur_feature[0])
|
| 325 |
+
|
| 326 |
+
return merged_image_features
|
| 327 |
+
|
| 328 |
+
def get_multimodal_embeddings(self, **kwargs):
|
| 329 |
+
image_input = self._parse_and_validate_image_input(**kwargs)
|
| 330 |
+
if image_input is None:
|
| 331 |
+
return None
|
| 332 |
+
vision_embeddings = self._process_image_input(image_input)
|
| 333 |
+
return vision_embeddings
|
| 334 |
+
|
| 335 |
+
@can_return_tuple
|
| 336 |
+
def forward(
|
| 337 |
+
self,
|
| 338 |
+
input_ids: torch.LongTensor = None,
|
| 339 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 340 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 341 |
+
past_key_values: Optional[Union[Cache, list[torch.FloatTensor]]] = None,
|
| 342 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 343 |
+
labels: Optional[torch.LongTensor] = None,
|
| 344 |
+
use_cache: Optional[bool] = None,
|
| 345 |
+
output_attentions: Optional[bool] = None,
|
| 346 |
+
output_hidden_states: Optional[bool] = None,
|
| 347 |
+
return_dict: Optional[bool] = None,
|
| 348 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 349 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
| 350 |
+
images: Optional[list[Image.Image]] = None,
|
| 351 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 352 |
+
) -> Union[tuple, StepVLCausalLMOutputWithPast]:
|
| 353 |
+
r"""
|
| 354 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 355 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 356 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 357 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 358 |
+
Example:
|
| 359 |
+
```python
|
| 360 |
+
>>> from transformers import AutoTokenizer, Llama4ForCausalLM
|
| 361 |
+
>>> model = Llama4ForCausalLM.from_pretrained("meta-llama4/Llama4-2-7b-hf")
|
| 362 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("meta-llama4/Llama4-2-7b-hf")
|
| 363 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
| 364 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
| 365 |
+
>>> # Generate
|
| 366 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 367 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 368 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
| 369 |
+
```"""
|
| 370 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 371 |
+
output_hidden_states = (
|
| 372 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 373 |
+
)
|
| 374 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 375 |
+
|
| 376 |
+
if inputs_embeds is None:
|
| 377 |
+
input_ids = input_ids
|
| 378 |
+
vision_embeddings = self.get_multimodal_embeddings(**kwargs)
|
| 379 |
+
inputs_embeds = self.get_input_embeddings(input_ids,
|
| 380 |
+
vision_embeddings)
|
| 381 |
+
input_ids = None
|
| 382 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 383 |
+
outputs = self.language_model(
|
| 384 |
+
input_ids=None,
|
| 385 |
+
position_ids=position_ids,
|
| 386 |
+
attention_mask=attention_mask,
|
| 387 |
+
past_key_values=past_key_values,
|
| 388 |
+
inputs_embeds=inputs_embeds,
|
| 389 |
+
use_cache=use_cache,
|
| 390 |
+
output_attentions=output_attentions,
|
| 391 |
+
output_hidden_states=output_hidden_states,
|
| 392 |
+
return_dict=True,
|
| 393 |
+
cache_position=cache_position,
|
| 394 |
+
**kwargs,
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
output = StepVLCausalLMOutputWithPast(
|
| 398 |
+
last_hidden_state=outputs.last_hidden_state,
|
| 399 |
+
past_key_values=outputs.past_key_values,
|
| 400 |
+
attentions=outputs.attentions,
|
| 401 |
+
|
| 402 |
+
)
|
| 403 |
+
return output if return_dict else output.to_tuple()
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
class Step3VL10BForCausalLM(StepRoboticsPreTrainedModel, GenerationMixin):
|
| 408 |
+
_checkpoint_conversion_mapping = {
|
| 409 |
+
"^vision_model": "model.vision_model",
|
| 410 |
+
r"^model(?!\.(language_model|vision_model))": "model.language_model",
|
| 411 |
+
"^vit_large_projector": "model.vit_large_projector"
|
| 412 |
+
}
|
| 413 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 414 |
+
config: StepRoboticsConfig
|
| 415 |
+
|
| 416 |
+
def __init__(self, config: StepRoboticsConfig):
|
| 417 |
+
super().__init__(config)
|
| 418 |
+
self.model = StepRoboticsModel(config)
|
| 419 |
+
self.lm_head = nn.Linear(config.hidden_size, config.text_config.vocab_size, bias=False)
|
| 420 |
+
|
| 421 |
+
self.post_init()
|
| 422 |
+
|
| 423 |
+
def get_input_embeddings(self):
|
| 424 |
+
return self.model.get_input_embeddings()
|
| 425 |
+
|
| 426 |
+
def set_input_embeddings(self, value):
|
| 427 |
+
self.model.set_input_embeddings(value)
|
| 428 |
+
|
| 429 |
+
def get_output_embeddings(self):
|
| 430 |
+
return self.model.get_output_embeddings()
|
| 431 |
+
|
| 432 |
+
def set_output_embeddings(self, new_embeddings):
|
| 433 |
+
self.model.set_output_embeddings(new_embeddings)
|
| 434 |
+
|
| 435 |
+
def set_decoder(self, decoder):
|
| 436 |
+
self.model.set_decoder(decoder)
|
| 437 |
+
|
| 438 |
+
def get_decoder(self):
|
| 439 |
+
return self.model.get_decoder()
|
| 440 |
+
|
| 441 |
+
@property
|
| 442 |
+
def language_model(self):
|
| 443 |
+
return self.model.language_model
|
| 444 |
+
|
| 445 |
+
@property
|
| 446 |
+
def visual(self):
|
| 447 |
+
return self.model.visual
|
| 448 |
+
|
| 449 |
+
def forward(
|
| 450 |
+
self,
|
| 451 |
+
input_ids: torch.LongTensor = None,
|
| 452 |
+
num_patches = None,
|
| 453 |
+
patch_pixel_values = None,
|
| 454 |
+
patch_newline_mask = None,
|
| 455 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 456 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 457 |
+
past_key_values: Optional[Cache] = None,
|
| 458 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 459 |
+
labels: Optional[torch.LongTensor] = None,
|
| 460 |
+
use_cache: Optional[bool] = None,
|
| 461 |
+
output_attentions: Optional[bool] = None,
|
| 462 |
+
output_hidden_states: Optional[bool] = None,
|
| 463 |
+
return_dict: Optional[bool] = None,
|
| 464 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 465 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 466 |
+
) -> Union[tuple, StepVLCausalLMOutputWithPast]:
|
| 467 |
+
r"""
|
| 468 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 469 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 470 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 471 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 472 |
+
Example:
|
| 473 |
+
```python
|
| 474 |
+
>>> from PIL import Image
|
| 475 |
+
>>> import requests
|
| 476 |
+
>>> from transformers import AutoProcessor, LlavaForConditionalGeneration
|
| 477 |
+
>>> model = LlavaForConditionalGeneration.from_pretrained("llava-hf/llava-1.5-7b-hf")
|
| 478 |
+
>>> processor = AutoProcessor.from_pretrained("llava-hf/llava-1.5-7b-hf")
|
| 479 |
+
>>> prompt = "USER: <image>\nWhat's the content of the image? ASSISTANT:"
|
| 480 |
+
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
|
| 481 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 482 |
+
>>> inputs = processor(images=image, text=prompt, return_tensors="pt")
|
| 483 |
+
>>> # Generate
|
| 484 |
+
>>> generate_ids = model.generate(**inputs, max_new_tokens=15)
|
| 485 |
+
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 486 |
+
"USER: \nWhat's the content of the image? ASSISTANT: The image features a busy city street with a stop sign prominently displayed"
|
| 487 |
+
```"""
|
| 488 |
+
|
| 489 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 490 |
+
output_hidden_states = (
|
| 491 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
outputs = self.model(
|
| 495 |
+
input_ids=input_ids,
|
| 496 |
+
num_patches = num_patches,
|
| 497 |
+
patch_pixel_values = patch_pixel_values,
|
| 498 |
+
patch_newline_mask=patch_newline_mask,
|
| 499 |
+
position_ids=position_ids,
|
| 500 |
+
attention_mask=attention_mask,
|
| 501 |
+
past_key_values=past_key_values,
|
| 502 |
+
inputs_embeds=inputs_embeds,
|
| 503 |
+
use_cache=use_cache,
|
| 504 |
+
output_attentions=output_attentions,
|
| 505 |
+
output_hidden_states=output_hidden_states,
|
| 506 |
+
return_dict=return_dict,
|
| 507 |
+
cache_position=cache_position,
|
| 508 |
+
**kwargs,
|
| 509 |
+
)
|
| 510 |
+
|
| 511 |
+
hidden_states = outputs.last_hidden_state
|
| 512 |
+
logits = self.lm_head(hidden_states)
|
| 513 |
+
|
| 514 |
+
los = None
|
| 515 |
+
if labels is not None:
|
| 516 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size)
|
| 517 |
+
|
| 518 |
+
return StepVLCausalLMOutputWithPast(
|
| 519 |
+
logits=logits,
|
| 520 |
+
)
|
| 521 |
+
|
| 522 |
+
def prepare_inputs_for_generation(
|
| 523 |
+
self,
|
| 524 |
+
input_ids,
|
| 525 |
+
past_key_values=None,
|
| 526 |
+
inputs_embeds=None,
|
| 527 |
+
pixel_values=None,
|
| 528 |
+
attention_mask=None,
|
| 529 |
+
cache_position=None,
|
| 530 |
+
logits_to_keep=None,
|
| 531 |
+
**kwargs,
|
| 532 |
+
):
|
| 533 |
+
# Overwritten -- in specific circumstances we don't want to forward image inputs to the model
|
| 534 |
+
|
| 535 |
+
model_inputs = super().prepare_inputs_for_generation(
|
| 536 |
+
input_ids,
|
| 537 |
+
past_key_values=past_key_values,
|
| 538 |
+
inputs_embeds=inputs_embeds,
|
| 539 |
+
attention_mask=attention_mask,
|
| 540 |
+
cache_position=cache_position,
|
| 541 |
+
logits_to_keep=logits_to_keep,
|
| 542 |
+
**kwargs,
|
| 543 |
+
)
|
| 544 |
+
|
| 545 |
+
if cache_position[0] == 0:
|
| 546 |
+
# If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
|
| 547 |
+
# Otherwise we need pixel values to be passed to model
|
| 548 |
+
model_inputs["pixel_values"] = pixel_values
|
| 549 |
+
|
| 550 |
+
return model_inputs
|
| 551 |
+
|
| 552 |
+
def _fix_state_dict_key_on_load(self, key: str) -> tuple[str, bool]:
|
| 553 |
+
if key.startswith("language_model."):
|
| 554 |
+
return key[len("language_model."):], True
|
| 555 |
+
|
| 556 |
+
return key, False
|
| 557 |
+
|
processing_step3.py
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import BaseImageProcessor, ImageProcessingMixin
|
| 2 |
+
from transformers.processing_utils import ImagesKwargs, MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack, VideosKwargs
|
| 3 |
+
import math
|
| 4 |
+
from typing import Iterable, Optional, Tuple, List, TypedDict, Literal, Union, overload
|
| 5 |
+
|
| 6 |
+
from PIL import Image
|
| 7 |
+
import torch
|
| 8 |
+
import numpy as np
|
| 9 |
+
import torchvision
|
| 10 |
+
from torch import nn
|
| 11 |
+
from torch.nn import functional as F, LayerNorm
|
| 12 |
+
from torchvision.transforms.functional import InterpolationMode
|
| 13 |
+
from transformers.activations import ACT2FN
|
| 14 |
+
from torchvision import transforms
|
| 15 |
+
from torchvision.transforms.functional import InterpolationMode
|
| 16 |
+
from transformers.feature_extraction_utils import BatchFeature, TensorType
|
| 17 |
+
from transformers.image_utils import ImageInput
|
| 18 |
+
from transformers.processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
|
| 19 |
+
from math import ceil
|
| 20 |
+
from itertools import product
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
MAX_IMAGE_SIZE: int = 3024
|
| 25 |
+
|
| 26 |
+
class Step3VLImagePixelInputs(TypedDict):
|
| 27 |
+
type: Literal["pixel_values"]
|
| 28 |
+
pixel_values: torch.Tensor
|
| 29 |
+
patch_pixel_values: Optional[torch.Tensor]
|
| 30 |
+
num_patches: list[int]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class Step3VLImageEmbeddingInputs(TypedDict):
|
| 34 |
+
type: Literal["image_embeds"]
|
| 35 |
+
image_embeds: torch.Tensor
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
ImageWithPatches = tuple[Image.Image, list[Image.Image], list[int] | None]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class GPUToTensor(torch.nn.Module):
|
| 42 |
+
|
| 43 |
+
def forward(self, raw_image: Union[np.ndarray,
|
| 44 |
+
Image.Image]) -> torch.Tensor:
|
| 45 |
+
if isinstance(raw_image, Image.Image):
|
| 46 |
+
return transforms.ToTensor()(raw_image)
|
| 47 |
+
if raw_image.ndim == 2:
|
| 48 |
+
raw_image = raw_image[:, :, None].repeat(3, -1)
|
| 49 |
+
if torch.cuda.is_available():
|
| 50 |
+
device = torch.device("cuda")
|
| 51 |
+
else:
|
| 52 |
+
device = torch.device("cpu")
|
| 53 |
+
image_tensor = torch.from_numpy(raw_image).to(device)
|
| 54 |
+
image_tensor = torch.permute(image_tensor, (2, 0, 1)).contiguous()
|
| 55 |
+
if image_tensor.dtype == torch.uint8:
|
| 56 |
+
image_tensor = image_tensor.to(torch.float32).div(255)
|
| 57 |
+
return image_tensor
|
| 58 |
+
|
| 59 |
+
class Step3VisionProcessor(BaseImageProcessor):
|
| 60 |
+
|
| 61 |
+
def __init__(self, size, interpolation_mode="bicubic", patch_size=None):
|
| 62 |
+
mean = [0.48145466, 0.4578275, 0.40821073]
|
| 63 |
+
std = [0.26862954, 0.26130258, 0.27577711]
|
| 64 |
+
patch_size = patch_size if patch_size is not None else size
|
| 65 |
+
|
| 66 |
+
self.transform = transforms.Compose([
|
| 67 |
+
GPUToTensor(),
|
| 68 |
+
transforms.Normalize(mean, std),
|
| 69 |
+
transforms.Resize(
|
| 70 |
+
(size, size),
|
| 71 |
+
interpolation=InterpolationMode.BICUBIC if interpolation_mode
|
| 72 |
+
== "bicubic" else InterpolationMode.BILINEAR,
|
| 73 |
+
antialias=True),
|
| 74 |
+
])
|
| 75 |
+
|
| 76 |
+
self.patch_transform = transforms.Compose([
|
| 77 |
+
GPUToTensor(),
|
| 78 |
+
transforms.Normalize(mean, std),
|
| 79 |
+
transforms.Resize(
|
| 80 |
+
(patch_size, patch_size),
|
| 81 |
+
interpolation=InterpolationMode.BICUBIC if interpolation_mode
|
| 82 |
+
== "bicubic" else InterpolationMode.BILINEAR,
|
| 83 |
+
antialias=True),
|
| 84 |
+
]) if patch_size is not None else None
|
| 85 |
+
|
| 86 |
+
def __call__(self, image, is_patch=False):
|
| 87 |
+
if is_patch:
|
| 88 |
+
return {"pixel_values": self.patch_transform(image).unsqueeze(0)}
|
| 89 |
+
else:
|
| 90 |
+
return {"pixel_values": self.transform(image).unsqueeze(0)}
|
| 91 |
+
|
| 92 |
+
class ImagePatcher:
|
| 93 |
+
def determine_window_size(self, long: int, short: int) -> int:
|
| 94 |
+
if long <= 728:
|
| 95 |
+
return short if long / short > 1.5 else 0
|
| 96 |
+
return min(short, 504) if long / short > 4 else 504
|
| 97 |
+
def slide_window(
|
| 98 |
+
self,
|
| 99 |
+
width: int,
|
| 100 |
+
height: int,
|
| 101 |
+
sizes: list[tuple[int, int]],
|
| 102 |
+
steps: list[tuple[int, int]],
|
| 103 |
+
img_rate_thr: float = 0.6,
|
| 104 |
+
) -> tuple[list[tuple[int, int, int, int]], tuple[int, int]]:
|
| 105 |
+
assert 1 >= img_rate_thr >= 0, "The `in_rate_thr` should lie in 0~1"
|
| 106 |
+
windows = []
|
| 107 |
+
# Sliding windows.
|
| 108 |
+
for size, step in zip(sizes, steps):
|
| 109 |
+
size_w, size_h = size
|
| 110 |
+
step_w, step_h = step
|
| 111 |
+
|
| 112 |
+
x_num = 1 if width <= size_w else ceil((width - size_w) / step_w +
|
| 113 |
+
1)
|
| 114 |
+
x_start = [step_w * i for i in range(x_num)]
|
| 115 |
+
if len(x_start) > 1 and x_start[-1] + size_w > width:
|
| 116 |
+
x_start[-1] = width - size_w
|
| 117 |
+
|
| 118 |
+
y_num = 1 if height <= size_h else ceil((height - size_h) /
|
| 119 |
+
step_h + 1)
|
| 120 |
+
y_start = [step_h * i for i in range(y_num)]
|
| 121 |
+
if len(y_start) > 1 and y_start[-1] + size_h > height:
|
| 122 |
+
y_start[-1] = height - size_h
|
| 123 |
+
|
| 124 |
+
start = np.array(list(product(y_start, x_start)), dtype=int)
|
| 125 |
+
start[:, [0, 1]] = start[:, [1, 0]]
|
| 126 |
+
windows.append(np.concatenate([start, start + size], axis=1))
|
| 127 |
+
windows = np.concatenate(windows, axis=0)
|
| 128 |
+
|
| 129 |
+
return [(int(box[0]), int(box[1]), int(box[2] - box[0]),
|
| 130 |
+
int(box[3] - box[1])) for box in windows], (x_num, y_num)
|
| 131 |
+
|
| 132 |
+
def square_pad(self, img: Image.Image) -> Image.Image:
|
| 133 |
+
w, h = img.size
|
| 134 |
+
if w == h:
|
| 135 |
+
return img
|
| 136 |
+
size = max(w, h)
|
| 137 |
+
padded = Image.new(img.mode, (size, size), 0)
|
| 138 |
+
padded.paste(img, (0, 0))
|
| 139 |
+
return padded
|
| 140 |
+
|
| 141 |
+
def get_image_size_for_padding(self, img_width: int,
|
| 142 |
+
img_height: int) -> tuple[int, int]:
|
| 143 |
+
ratio = img_width / img_height
|
| 144 |
+
if min(img_height, img_width) < 32 and (ratio > 4 or ratio < 1 / 4):
|
| 145 |
+
new_size = max(img_height, img_width)
|
| 146 |
+
return new_size, new_size
|
| 147 |
+
return img_width, img_height
|
| 148 |
+
|
| 149 |
+
def get_image_size_for_preprocess(self, img_width: int,
|
| 150 |
+
img_height: int) -> tuple[int, int]:
|
| 151 |
+
|
| 152 |
+
if max(img_height, img_width) > MAX_IMAGE_SIZE:
|
| 153 |
+
scale_factor = MAX_IMAGE_SIZE / max(img_height, img_width)
|
| 154 |
+
img_width = int(img_width * scale_factor)
|
| 155 |
+
img_height = int(img_height * scale_factor)
|
| 156 |
+
return img_width, img_height
|
| 157 |
+
|
| 158 |
+
def get_image_size_for_crop(self, img_width: int, img_height: int,
|
| 159 |
+
window_size: int):
|
| 160 |
+
w_ratio = img_width / window_size
|
| 161 |
+
h_ratio = img_height / window_size
|
| 162 |
+
|
| 163 |
+
if w_ratio < 1:
|
| 164 |
+
width_new = img_width
|
| 165 |
+
else:
|
| 166 |
+
decimal_w = w_ratio - img_width // window_size
|
| 167 |
+
w_ratio = int(w_ratio) + 1 if decimal_w > 0.2 else int(w_ratio)
|
| 168 |
+
width_new = window_size * w_ratio
|
| 169 |
+
if h_ratio < 1:
|
| 170 |
+
height_new = img_height
|
| 171 |
+
else:
|
| 172 |
+
decimal_h = h_ratio - img_height // window_size
|
| 173 |
+
h_ratio = int(h_ratio) + 1 if decimal_h > 0.2 else int(h_ratio)
|
| 174 |
+
height_new = window_size * h_ratio
|
| 175 |
+
return int(width_new), int(height_new)
|
| 176 |
+
|
| 177 |
+
def patch_crop(self, img: Image.Image, i: int, j: int, th: int, tw: int):
|
| 178 |
+
target = img.crop((j, i, j + tw, i + th))
|
| 179 |
+
return target
|
| 180 |
+
|
| 181 |
+
def get_num_patches(self, img_width: int,
|
| 182 |
+
img_height: int) -> tuple[int, int]:
|
| 183 |
+
img_width, img_height = self.get_image_size_for_padding(
|
| 184 |
+
img_width, img_height)
|
| 185 |
+
img_width, img_height = self.get_image_size_for_preprocess(
|
| 186 |
+
img_width, img_height)
|
| 187 |
+
window_size = self.determine_window_size(max(img_height, img_width),
|
| 188 |
+
min(img_height, img_width))
|
| 189 |
+
if window_size == 0:
|
| 190 |
+
return 0, 0
|
| 191 |
+
else:
|
| 192 |
+
img_width, img_height = self.get_image_size_for_crop(
|
| 193 |
+
img_width, img_height, window_size)
|
| 194 |
+
center_list, (x_num, y_num) = self.slide_window(
|
| 195 |
+
img_width, img_height, [(window_size, window_size)],
|
| 196 |
+
[(window_size, window_size)])
|
| 197 |
+
full_rows = (len(center_list) - 1) // x_num + 1
|
| 198 |
+
if len(center_list) > 0 and len(center_list) % x_num == 0:
|
| 199 |
+
full_rows -= 1
|
| 200 |
+
return len(center_list), full_rows
|
| 201 |
+
|
| 202 |
+
def __call__(
|
| 203 |
+
self, img: Image.Image
|
| 204 |
+
) -> tuple[Image.Image, list[Image.Image], list[bool] | None]:
|
| 205 |
+
img_width, img_height = img.size
|
| 206 |
+
new_img_width, new_img_height = self.get_image_size_for_padding(
|
| 207 |
+
img_width, img_height)
|
| 208 |
+
if new_img_width != img_width or new_img_height != img_height:
|
| 209 |
+
img = self.square_pad(img)
|
| 210 |
+
img_width, img_height = img.size
|
| 211 |
+
|
| 212 |
+
new_img_width, new_img_height = self.get_image_size_for_preprocess(
|
| 213 |
+
img_width, img_height)
|
| 214 |
+
img = img.resize((new_img_width, new_img_height),
|
| 215 |
+
Image.Resampling.BILINEAR)
|
| 216 |
+
window_size = self.determine_window_size(
|
| 217 |
+
max(new_img_height, new_img_width),
|
| 218 |
+
min(new_img_height, new_img_width))
|
| 219 |
+
|
| 220 |
+
if window_size == 0:
|
| 221 |
+
return img, [], None
|
| 222 |
+
else:
|
| 223 |
+
new_img_width, new_img_height = self.get_image_size_for_crop(
|
| 224 |
+
new_img_width, new_img_height, window_size)
|
| 225 |
+
if (new_img_width, new_img_height) != (img_width, img_height):
|
| 226 |
+
img_for_crop = img.resize((new_img_width, new_img_height),
|
| 227 |
+
Image.Resampling.BILINEAR)
|
| 228 |
+
else:
|
| 229 |
+
img_for_crop = img
|
| 230 |
+
|
| 231 |
+
patches = []
|
| 232 |
+
newlines = []
|
| 233 |
+
center_list, (x_num, y_num) = self.slide_window(
|
| 234 |
+
new_img_width, new_img_height, [(window_size, window_size)],
|
| 235 |
+
[(window_size, window_size)])
|
| 236 |
+
for patch_id, center_lf_point in enumerate(center_list):
|
| 237 |
+
x, y, patch_w, patch_h = center_lf_point
|
| 238 |
+
big_patch = self.patch_crop(img_for_crop, y, x, patch_h,
|
| 239 |
+
patch_w)
|
| 240 |
+
patches.append(big_patch)
|
| 241 |
+
if (patch_id + 1) % x_num == 0:
|
| 242 |
+
newlines.append(patch_id)
|
| 243 |
+
|
| 244 |
+
if newlines and newlines[-1] == len(patches) - 1:
|
| 245 |
+
newlines.pop()
|
| 246 |
+
|
| 247 |
+
return img, patches, [i in newlines for i in range(len(patches))] if len(patches) > 0 else None
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
class Step3VLProcessor(ProcessorMixin):
|
| 253 |
+
# Align ProcessorMixin with our custom components.
|
| 254 |
+
# We only have an image processor (not a feature extractor) plus a tokenizer.
|
| 255 |
+
attributes = ["tokenizer"]
|
| 256 |
+
tokenizer_class = "AutoTokenizer"
|
| 257 |
+
|
| 258 |
+
def __init__(
|
| 259 |
+
self,
|
| 260 |
+
tokenizer=None,
|
| 261 |
+
chat_template=None,
|
| 262 |
+
**kwargs
|
| 263 |
+
) -> None:
|
| 264 |
+
self.image_size = 728
|
| 265 |
+
self.patch_size = 504
|
| 266 |
+
|
| 267 |
+
self.image_preprocessor = Step3VisionProcessor(self.image_size,
|
| 268 |
+
"bilinear",
|
| 269 |
+
self.patch_size)
|
| 270 |
+
|
| 271 |
+
self.num_image_feature_size = 169
|
| 272 |
+
self.num_patch_feature_size = 81
|
| 273 |
+
self.image_token = "<im_patch>"
|
| 274 |
+
self.image_feature_placeholder = (self.image_token *
|
| 275 |
+
self.num_image_feature_size)
|
| 276 |
+
self.patch_feature_placeholder = (self.image_token *
|
| 277 |
+
self.num_patch_feature_size)
|
| 278 |
+
super().__init__(tokenizer=tokenizer, chat_template=chat_template, **kwargs)
|
| 279 |
+
self.patcher = ImagePatcher()
|
| 280 |
+
|
| 281 |
+
@property
|
| 282 |
+
def image_token_id(self) -> int:
|
| 283 |
+
return self.tokenizer.get_vocab()[self.image_token]
|
| 284 |
+
|
| 285 |
+
def get_num_image_tokens(self, img_width: int, img_height: int) -> int:
|
| 286 |
+
num_patches, num_newlines = self.patcher.get_num_patches(
|
| 287 |
+
img_width, img_height)
|
| 288 |
+
|
| 289 |
+
return num_patches * (
|
| 290 |
+
self.num_patch_feature_size +
|
| 291 |
+
2) + self.num_image_feature_size + 2 + num_newlines
|
| 292 |
+
|
| 293 |
+
def _split_images(self,
|
| 294 |
+
images: list[Image.Image]) -> list[ImageWithPatches]:
|
| 295 |
+
result = []
|
| 296 |
+
for img in images:
|
| 297 |
+
result.append(self.patcher(img))
|
| 298 |
+
return result
|
| 299 |
+
|
| 300 |
+
def _convert_images_to_pixel_values(
|
| 301 |
+
self,
|
| 302 |
+
images: list[Image.Image],
|
| 303 |
+
is_patch: bool = False,
|
| 304 |
+
) -> list[torch.Tensor]:
|
| 305 |
+
return [
|
| 306 |
+
self.image_preprocessor(img, is_patch=is_patch)["pixel_values"]
|
| 307 |
+
for img in images
|
| 308 |
+
]
|
| 309 |
+
|
| 310 |
+
def _get_patch_repl(
|
| 311 |
+
self,
|
| 312 |
+
num_patches: int,
|
| 313 |
+
patch_newline_mask: list[bool] | None,
|
| 314 |
+
) -> tuple[str, list[int]]:
|
| 315 |
+
text = ""
|
| 316 |
+
token_ids = []
|
| 317 |
+
for i in range(num_patches):
|
| 318 |
+
assert len(patch_newline_mask) == num_patches
|
| 319 |
+
text += f"<patch_start>{self.patch_feature_placeholder}<patch_end>"
|
| 320 |
+
token_ids.extend(
|
| 321 |
+
[self.tokenizer.convert_tokens_to_ids("<patch_start>")] +
|
| 322 |
+
[self.image_token_id] * self.num_patch_feature_size +
|
| 323 |
+
[self.tokenizer.convert_tokens_to_ids("<patch_end>")])
|
| 324 |
+
if patch_newline_mask and patch_newline_mask[i]:
|
| 325 |
+
text += "<patch_newline>"
|
| 326 |
+
token_ids.append(
|
| 327 |
+
self.tokenizer.convert_tokens_to_ids("<patch_newline>"))
|
| 328 |
+
return text, token_ids
|
| 329 |
+
|
| 330 |
+
def _get_image_repl(
|
| 331 |
+
self,
|
| 332 |
+
num_images: int,
|
| 333 |
+
) -> tuple[str, list[int]]:
|
| 334 |
+
text = f"<im_start>{self.image_feature_placeholder}<im_end>"
|
| 335 |
+
token_ids = [
|
| 336 |
+
self.tokenizer.convert_tokens_to_ids("<im_start>")
|
| 337 |
+
] + [self.image_token_id] * self.num_image_feature_size + [
|
| 338 |
+
self.tokenizer.convert_tokens_to_ids("<im_end>")
|
| 339 |
+
]
|
| 340 |
+
return text * num_images, token_ids * num_images
|
| 341 |
+
|
| 342 |
+
def _get_image_repl_features(
|
| 343 |
+
self,
|
| 344 |
+
num_images: int,
|
| 345 |
+
num_patches: int,
|
| 346 |
+
patch_new_line_idx: Optional[list[bool]],
|
| 347 |
+
) -> tuple[str, list[int]]:
|
| 348 |
+
if num_patches > 0:
|
| 349 |
+
patch_repl, patch_repl_ids = self._get_patch_repl(
|
| 350 |
+
num_patches, patch_new_line_idx)
|
| 351 |
+
else:
|
| 352 |
+
patch_repl = ""
|
| 353 |
+
patch_repl_ids = []
|
| 354 |
+
image_repl, image_repl_ids = self._get_image_repl(num_images)
|
| 355 |
+
return patch_repl + image_repl, patch_repl_ids + image_repl_ids
|
| 356 |
+
|
| 357 |
+
def replace_placeholder(self, text: str, placeholder: str,
|
| 358 |
+
repls: list[str]) -> str:
|
| 359 |
+
parts = text.split(placeholder)
|
| 360 |
+
|
| 361 |
+
if len(parts) - 1 != len(repls):
|
| 362 |
+
raise ValueError(
|
| 363 |
+
"The number of placeholders does not match the number of replacements." # noqa: E501
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
result = [parts[0]]
|
| 367 |
+
for i, repl in enumerate(repls):
|
| 368 |
+
result.append(repl)
|
| 369 |
+
result.append(parts[i + 1])
|
| 370 |
+
|
| 371 |
+
return "".join(result)
|
| 372 |
+
|
| 373 |
+
def __call__(
|
| 374 |
+
self,
|
| 375 |
+
text: Optional[Union[str, list[str]]] = None,
|
| 376 |
+
images: ImageInput | None = None,
|
| 377 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 378 |
+
**kwargs,
|
| 379 |
+
) -> BatchFeature:
|
| 380 |
+
|
| 381 |
+
if images is not None:
|
| 382 |
+
images = self.image_preprocessor.fetch_images(images)
|
| 383 |
+
if text is None:
|
| 384 |
+
text = []
|
| 385 |
+
if not isinstance(text, list):
|
| 386 |
+
text = [text]
|
| 387 |
+
if images is None:
|
| 388 |
+
images = []
|
| 389 |
+
elif not isinstance(images, list):
|
| 390 |
+
images = [images]
|
| 391 |
+
elif isinstance(images[0], list):
|
| 392 |
+
images = images[0]
|
| 393 |
+
|
| 394 |
+
if len(images) == 0:
|
| 395 |
+
image_inputs = {}
|
| 396 |
+
text_inputs = self.tokenizer(text)
|
| 397 |
+
else:
|
| 398 |
+
splitted_images_data = self._split_images(images)
|
| 399 |
+
pixel_values_lst = []
|
| 400 |
+
patch_pixel_values_lst = []
|
| 401 |
+
patch_newline_mask_lst = []
|
| 402 |
+
image_repl_str_lst = []
|
| 403 |
+
image_repl_ids_lst = []
|
| 404 |
+
num_patches = []
|
| 405 |
+
for raw_img, img_patches, patch_newline_mask in splitted_images_data: # noqa: E501
|
| 406 |
+
pixel_values_lst.extend(
|
| 407 |
+
self._convert_images_to_pixel_values([raw_img]))
|
| 408 |
+
|
| 409 |
+
if len(img_patches) > 0:
|
| 410 |
+
patch_pixel_values_lst.extend(
|
| 411 |
+
self._convert_images_to_pixel_values(img_patches,
|
| 412 |
+
is_patch=True))
|
| 413 |
+
num_patches.append(len(img_patches))
|
| 414 |
+
|
| 415 |
+
image_repl_str, image_repl_ids = self._get_image_repl_features(
|
| 416 |
+
1, len(img_patches), patch_newline_mask)
|
| 417 |
+
image_repl_str_lst.append(image_repl_str)
|
| 418 |
+
image_repl_ids_lst.extend(image_repl_ids)
|
| 419 |
+
|
| 420 |
+
if patch_newline_mask is not None:
|
| 421 |
+
patch_newline_mask_lst.extend(patch_newline_mask)
|
| 422 |
+
|
| 423 |
+
image_inputs = {
|
| 424 |
+
"pixel_values": torch.cat(pixel_values_lst),
|
| 425 |
+
"num_patches": num_patches,
|
| 426 |
+
}
|
| 427 |
+
if patch_pixel_values_lst:
|
| 428 |
+
image_inputs["patch_pixel_values"] = torch.cat(
|
| 429 |
+
patch_pixel_values_lst)
|
| 430 |
+
if patch_newline_mask_lst:
|
| 431 |
+
image_inputs["patch_newline_mask"] = torch.tensor(
|
| 432 |
+
patch_newline_mask_lst, dtype=torch.bool)
|
| 433 |
+
|
| 434 |
+
text = [
|
| 435 |
+
self.replace_placeholder(t, self.image_token,
|
| 436 |
+
image_repl_str_lst) for t in text
|
| 437 |
+
]
|
| 438 |
+
text_inputs = self.tokenizer(text)
|
| 439 |
+
|
| 440 |
+
return BatchFeature(
|
| 441 |
+
{
|
| 442 |
+
**text_inputs,
|
| 443 |
+
**image_inputs,
|
| 444 |
+
},
|
| 445 |
+
tensor_type=return_tensors,
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Gemma
|
| 449 |
+
def batch_decode(self, *args, **kwargs):
|
| 450 |
+
"""
|
| 451 |
+
This method forwards all its arguments to GemmaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
|
| 452 |
+
refer to the docstring of this method for more information.
|
| 453 |
+
"""
|
| 454 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
| 455 |
+
|
| 456 |
+
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Gemma
|
| 457 |
+
def decode(self, *args, **kwargs):
|
| 458 |
+
"""
|
| 459 |
+
This method forwards all its arguments to GemmaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
|
| 460 |
+
the docstring of this method for more information.
|
| 461 |
+
"""
|
| 462 |
+
return self.tokenizer.decode(*args, **kwargs)
|
| 463 |
+
|
| 464 |
+
__all__ = ["Step3VLProcessor"]
|
processor_config.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"auto_map": {
|
| 3 |
+
"AutoProcessor": "processing_step3.Step3VLProcessor"
|
| 4 |
+
}
|
| 5 |
+
}
|
| 6 |
+
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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",
|
| 5 |
+
"lstrip": false,
|
| 6 |
+
"normalized": false,
|
| 7 |
+
"rstrip": false,
|
| 8 |
+
"single_word": false
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"content": "<|im_end|>",
|
| 12 |
+
"lstrip": false,
|
| 13 |
+
"normalized": false,
|
| 14 |
+
"rstrip": false,
|
| 15 |
+
"single_word": false
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"content": "<|object_ref_start|>",
|
| 19 |
+
"lstrip": false,
|
| 20 |
+
"normalized": false,
|
| 21 |
+
"rstrip": false,
|
| 22 |
+
"single_word": false
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"content": "<|object_ref_end|>",
|
| 26 |
+
"lstrip": false,
|
| 27 |
+
"normalized": false,
|
| 28 |
+
"rstrip": false,
|
| 29 |
+
"single_word": false
|
| 30 |
+
},
|
| 31 |
+
{
|
| 32 |
+
"content": "<|box_start|>",
|
| 33 |
+
"lstrip": false,
|
| 34 |
+
"normalized": false,
|
| 35 |
+
"rstrip": false,
|
| 36 |
+
"single_word": false
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"content": "<|box_end|>",
|
| 40 |
+
"lstrip": false,
|
| 41 |
+
"normalized": false,
|
| 42 |
+
"rstrip": false,
|
| 43 |
+
"single_word": false
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"content": "<|quad_start|>",
|
| 47 |
+
"lstrip": false,
|
| 48 |
+
"normalized": false,
|
| 49 |
+
"rstrip": false,
|
| 50 |
+
"single_word": false
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"content": "<|quad_end|>",
|
| 54 |
+
"lstrip": false,
|
| 55 |
+
"normalized": false,
|
| 56 |
+
"rstrip": false,
|
| 57 |
+
"single_word": false
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"content": "<|vision_start|>",
|
| 61 |
+
"lstrip": false,
|
| 62 |
+
"normalized": false,
|
| 63 |
+
"rstrip": false,
|
| 64 |
+
"single_word": false
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"content": "<|vision_end|>",
|
| 68 |
+
"lstrip": false,
|
| 69 |
+
"normalized": false,
|
| 70 |
+
"rstrip": false,
|
| 71 |
+
"single_word": false
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"content": "<|vision_pad|>",
|
| 75 |
+
"lstrip": false,
|
| 76 |
+
"normalized": false,
|
| 77 |
+
"rstrip": false,
|
| 78 |
+
"single_word": false
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"content": "<|image_pad|>",
|
| 82 |
+
"lstrip": false,
|
| 83 |
+
"normalized": false,
|
| 84 |
+
"rstrip": false,
|
| 85 |
+
"single_word": false
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"content": "<|video_pad|>",
|
| 89 |
+
"lstrip": false,
|
| 90 |
+
"normalized": false,
|
| 91 |
+
"rstrip": false,
|
| 92 |
+
"single_word": false
|
| 93 |
+
},
|
| 94 |
+
{
|
| 95 |
+
"content": "<tool_calls>",
|
| 96 |
+
"lstrip": false,
|
| 97 |
+
"normalized": false,
|
| 98 |
+
"rstrip": false,
|
| 99 |
+
"single_word": false
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"content": "</tool_calls>",
|
| 103 |
+
"lstrip": false,
|
| 104 |
+
"normalized": false,
|
| 105 |
+
"rstrip": false,
|
| 106 |
+
"single_word": false
|
| 107 |
+
},
|
| 108 |
+
{
|
| 109 |
+
"content": "<|EOT|>",
|
| 110 |
+
"lstrip": false,
|
| 111 |
+
"normalized": false,
|
| 112 |
+
"rstrip": false,
|
| 113 |
+
"single_word": false
|
| 114 |
+
},
|
| 115 |
+
{
|
| 116 |
+
"content": "<|BOT|>",
|
| 117 |
+
"lstrip": false,
|
| 118 |
+
"normalized": false,
|
| 119 |
+
"rstrip": false,
|
| 120 |
+
"single_word": false
|
| 121 |
+
},
|
| 122 |
+
{
|
| 123 |
+
"content": "<|CALL_START|>",
|
| 124 |
+
"lstrip": false,
|
| 125 |
+
"normalized": false,
|
| 126 |
+
"rstrip": false,
|
| 127 |
+
"single_word": false
|
| 128 |
+
},
|
| 129 |
+
{
|
| 130 |
+
"content": "<|CALL_END|>",
|
| 131 |
+
"lstrip": false,
|
| 132 |
+
"normalized": false,
|
| 133 |
+
"rstrip": false,
|
| 134 |
+
"single_word": false
|
| 135 |
+
},
|
| 136 |
+
{
|
| 137 |
+
"content": "<|THINK_START|>",
|
| 138 |
+
"lstrip": false,
|
| 139 |
+
"normalized": false,
|
| 140 |
+
"rstrip": false,
|
| 141 |
+
"single_word": false
|
| 142 |
+
},
|
| 143 |
+
{
|
| 144 |
+
"content": "<|THINK_END|>",
|
| 145 |
+
"lstrip": false,
|
| 146 |
+
"normalized": false,
|
| 147 |
+
"rstrip": false,
|
| 148 |
+
"single_word": false
|
| 149 |
+
},
|
| 150 |
+
{
|
| 151 |
+
"content": "<|IMG_START|>",
|
| 152 |
+
"lstrip": false,
|
| 153 |
+
"normalized": false,
|
| 154 |
+
"rstrip": false,
|
| 155 |
+
"single_word": false
|
| 156 |
+
},
|
| 157 |
+
{
|
| 158 |
+
"content": "<|IMG_END|>",
|
| 159 |
+
"lstrip": false,
|
| 160 |
+
"normalized": false,
|
| 161 |
+
"rstrip": false,
|
| 162 |
+
"single_word": false
|
| 163 |
+
},
|
| 164 |
+
{
|
| 165 |
+
"content": "<im_patch>",
|
| 166 |
+
"lstrip": false,
|
| 167 |
+
"normalized": false,
|
| 168 |
+
"rstrip": false,
|
| 169 |
+
"single_word": false
|
| 170 |
+
},
|
| 171 |
+
{
|
| 172 |
+
"content": "<im_start>",
|
| 173 |
+
"lstrip": false,
|
| 174 |
+
"normalized": false,
|
| 175 |
+
"rstrip": false,
|
| 176 |
+
"single_word": false
|
| 177 |
+
},
|
| 178 |
+
{
|
| 179 |
+
"content": "<im_end>",
|
| 180 |
+
"lstrip": false,
|
| 181 |
+
"normalized": false,
|
| 182 |
+
"rstrip": false,
|
| 183 |
+
"single_word": false
|
| 184 |
+
},
|
| 185 |
+
{
|
| 186 |
+
"content": "<dream>",
|
| 187 |
+
"lstrip": false,
|
| 188 |
+
"normalized": false,
|
| 189 |
+
"rstrip": false,
|
| 190 |
+
"single_word": false
|
| 191 |
+
},
|
| 192 |
+
{
|
| 193 |
+
"content": "<dream_start>",
|
| 194 |
+
"lstrip": false,
|
| 195 |
+
"normalized": false,
|
| 196 |
+
"rstrip": false,
|
| 197 |
+
"single_word": false
|
| 198 |
+
},
|
| 199 |
+
{
|
| 200 |
+
"content": "<dream_end>",
|
| 201 |
+
"lstrip": false,
|
| 202 |
+
"normalized": false,
|
| 203 |
+
"rstrip": false,
|
| 204 |
+
"single_word": false
|
| 205 |
+
},
|
| 206 |
+
{
|
| 207 |
+
"content": "<|MASK_1e69f|>",
|
| 208 |
+
"lstrip": false,
|
| 209 |
+
"normalized": false,
|
| 210 |
+
"rstrip": false,
|
| 211 |
+
"single_word": false
|
| 212 |
+
},
|
| 213 |
+
{
|
| 214 |
+
"content": "<|UNMASK_1e69f|>",
|
| 215 |
+
"lstrip": false,
|
| 216 |
+
"normalized": false,
|
| 217 |
+
"rstrip": false,
|
| 218 |
+
"single_word": false
|
| 219 |
+
},
|
| 220 |
+
{
|
| 221 |
+
"content": "<video_start>",
|
| 222 |
+
"lstrip": false,
|
| 223 |
+
"normalized": false,
|
| 224 |
+
"rstrip": false,
|
| 225 |
+
"single_word": false
|
| 226 |
+
},
|
| 227 |
+
{
|
| 228 |
+
"content": "<video_end>",
|
| 229 |
+
"lstrip": false,
|
| 230 |
+
"normalized": false,
|
| 231 |
+
"rstrip": false,
|
| 232 |
+
"single_word": false
|
| 233 |
+
},
|
| 234 |
+
{
|
| 235 |
+
"content": "<patch_start>",
|
| 236 |
+
"lstrip": false,
|
| 237 |
+
"normalized": false,
|
| 238 |
+
"rstrip": false,
|
| 239 |
+
"single_word": false
|
| 240 |
+
},
|
| 241 |
+
{
|
| 242 |
+
"content": "<patch_end>",
|
| 243 |
+
"lstrip": false,
|
| 244 |
+
"normalized": false,
|
| 245 |
+
"rstrip": false,
|
| 246 |
+
"single_word": false
|
| 247 |
+
},
|
| 248 |
+
{
|
| 249 |
+
"content": "<patch_newline>",
|
| 250 |
+
"lstrip": false,
|
| 251 |
+
"normalized": false,
|
| 252 |
+
"rstrip": false,
|
| 253 |
+
"single_word": false
|
| 254 |
+
}
|
| 255 |
+
],
|
| 256 |
+
"eos_token": {
|
| 257 |
+
"content": "<|im_end|>",
|
| 258 |
+
"lstrip": false,
|
| 259 |
+
"normalized": false,
|
| 260 |
+
"rstrip": false,
|
| 261 |
+
"single_word": false
|
| 262 |
+
},
|
| 263 |
+
"pad_token": {
|
| 264 |
+
"content": "<|endoftext|>",
|
| 265 |
+
"lstrip": false,
|
| 266 |
+
"normalized": false,
|
| 267 |
+
"rstrip": false,
|
| 268 |
+
"single_word": false
|
| 269 |
+
}
|
| 270 |
+
}
|
tokenizer.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:439885437ceee7205faa72b808b543bb3fcd2f3df788a959aa3604d07a8f5c75
|
| 3 |
+
size 11426994
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,446 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_bos_token": false,
|
| 3 |
+
"add_prefix_space": false,
|
| 4 |
+
"added_tokens_decoder": {
|
| 5 |
+
"151643": {
|
| 6 |
+
"content": "<|endoftext|>",
|
| 7 |
+
"lstrip": false,
|
| 8 |
+
"normalized": false,
|
| 9 |
+
"rstrip": false,
|
| 10 |
+
"single_word": false,
|
| 11 |
+
"special": true
|
| 12 |
+
},
|
| 13 |
+
"151644": {
|
| 14 |
+
"content": "<|im_start|>",
|
| 15 |
+
"lstrip": false,
|
| 16 |
+
"normalized": false,
|
| 17 |
+
"rstrip": false,
|
| 18 |
+
"single_word": false,
|
| 19 |
+
"special": true
|
| 20 |
+
},
|
| 21 |
+
"151645": {
|
| 22 |
+
"content": "<|im_end|>",
|
| 23 |
+
"lstrip": false,
|
| 24 |
+
"normalized": false,
|
| 25 |
+
"rstrip": false,
|
| 26 |
+
"single_word": false,
|
| 27 |
+
"special": true
|
| 28 |
+
},
|
| 29 |
+
"151646": {
|
| 30 |
+
"content": "<|object_ref_start|>",
|
| 31 |
+
"lstrip": false,
|
| 32 |
+
"normalized": false,
|
| 33 |
+
"rstrip": false,
|
| 34 |
+
"single_word": false,
|
| 35 |
+
"special": true
|
| 36 |
+
},
|
| 37 |
+
"151647": {
|
| 38 |
+
"content": "<|object_ref_end|>",
|
| 39 |
+
"lstrip": false,
|
| 40 |
+
"normalized": false,
|
| 41 |
+
"rstrip": false,
|
| 42 |
+
"single_word": false,
|
| 43 |
+
"special": true
|
| 44 |
+
},
|
| 45 |
+
"151648": {
|
| 46 |
+
"content": "<|box_start|>",
|
| 47 |
+
"lstrip": false,
|
| 48 |
+
"normalized": false,
|
| 49 |
+
"rstrip": false,
|
| 50 |
+
"single_word": false,
|
| 51 |
+
"special": true
|
| 52 |
+
},
|
| 53 |
+
"151649": {
|
| 54 |
+
"content": "<|box_end|>",
|
| 55 |
+
"lstrip": false,
|
| 56 |
+
"normalized": false,
|
| 57 |
+
"rstrip": false,
|
| 58 |
+
"single_word": false,
|
| 59 |
+
"special": true
|
| 60 |
+
},
|
| 61 |
+
"151650": {
|
| 62 |
+
"content": "<|quad_start|>",
|
| 63 |
+
"lstrip": false,
|
| 64 |
+
"normalized": false,
|
| 65 |
+
"rstrip": false,
|
| 66 |
+
"single_word": false,
|
| 67 |
+
"special": true
|
| 68 |
+
},
|
| 69 |
+
"151651": {
|
| 70 |
+
"content": "<|quad_end|>",
|
| 71 |
+
"lstrip": false,
|
| 72 |
+
"normalized": false,
|
| 73 |
+
"rstrip": false,
|
| 74 |
+
"single_word": false,
|
| 75 |
+
"special": true
|
| 76 |
+
},
|
| 77 |
+
"151652": {
|
| 78 |
+
"content": "<|vision_start|>",
|
| 79 |
+
"lstrip": false,
|
| 80 |
+
"normalized": false,
|
| 81 |
+
"rstrip": false,
|
| 82 |
+
"single_word": false,
|
| 83 |
+
"special": true
|
| 84 |
+
},
|
| 85 |
+
"151653": {
|
| 86 |
+
"content": "<|vision_end|>",
|
| 87 |
+
"lstrip": false,
|
| 88 |
+
"normalized": false,
|
| 89 |
+
"rstrip": false,
|
| 90 |
+
"single_word": false,
|
| 91 |
+
"special": true
|
| 92 |
+
},
|
| 93 |
+
"151654": {
|
| 94 |
+
"content": "<|vision_pad|>",
|
| 95 |
+
"lstrip": false,
|
| 96 |
+
"normalized": false,
|
| 97 |
+
"rstrip": false,
|
| 98 |
+
"single_word": false,
|
| 99 |
+
"special": true
|
| 100 |
+
},
|
| 101 |
+
"151655": {
|
| 102 |
+
"content": "<|image_pad|>",
|
| 103 |
+
"lstrip": false,
|
| 104 |
+
"normalized": false,
|
| 105 |
+
"rstrip": false,
|
| 106 |
+
"single_word": false,
|
| 107 |
+
"special": true
|
| 108 |
+
},
|
| 109 |
+
"151656": {
|
| 110 |
+
"content": "<|video_pad|>",
|
| 111 |
+
"lstrip": false,
|
| 112 |
+
"normalized": false,
|
| 113 |
+
"rstrip": false,
|
| 114 |
+
"single_word": false,
|
| 115 |
+
"special": true
|
| 116 |
+
},
|
| 117 |
+
"151657": {
|
| 118 |
+
"content": "<tool_call>",
|
| 119 |
+
"lstrip": false,
|
| 120 |
+
"normalized": false,
|
| 121 |
+
"rstrip": false,
|
| 122 |
+
"single_word": false,
|
| 123 |
+
"special": false
|
| 124 |
+
},
|
| 125 |
+
"151658": {
|
| 126 |
+
"content": "</tool_call>",
|
| 127 |
+
"lstrip": false,
|
| 128 |
+
"normalized": false,
|
| 129 |
+
"rstrip": false,
|
| 130 |
+
"single_word": false,
|
| 131 |
+
"special": false
|
| 132 |
+
},
|
| 133 |
+
"151659": {
|
| 134 |
+
"content": "<|fim_prefix|>",
|
| 135 |
+
"lstrip": false,
|
| 136 |
+
"normalized": false,
|
| 137 |
+
"rstrip": false,
|
| 138 |
+
"single_word": false,
|
| 139 |
+
"special": false
|
| 140 |
+
},
|
| 141 |
+
"151660": {
|
| 142 |
+
"content": "<|fim_middle|>",
|
| 143 |
+
"lstrip": false,
|
| 144 |
+
"normalized": false,
|
| 145 |
+
"rstrip": false,
|
| 146 |
+
"single_word": false,
|
| 147 |
+
"special": false
|
| 148 |
+
},
|
| 149 |
+
"151661": {
|
| 150 |
+
"content": "<|fim_suffix|>",
|
| 151 |
+
"lstrip": false,
|
| 152 |
+
"normalized": false,
|
| 153 |
+
"rstrip": false,
|
| 154 |
+
"single_word": false,
|
| 155 |
+
"special": false
|
| 156 |
+
},
|
| 157 |
+
"151662": {
|
| 158 |
+
"content": "<|fim_pad|>",
|
| 159 |
+
"lstrip": false,
|
| 160 |
+
"normalized": false,
|
| 161 |
+
"rstrip": false,
|
| 162 |
+
"single_word": false,
|
| 163 |
+
"special": false
|
| 164 |
+
},
|
| 165 |
+
"151663": {
|
| 166 |
+
"content": "<|repo_name|>",
|
| 167 |
+
"lstrip": false,
|
| 168 |
+
"normalized": false,
|
| 169 |
+
"rstrip": false,
|
| 170 |
+
"single_word": false,
|
| 171 |
+
"special": false
|
| 172 |
+
},
|
| 173 |
+
"151664": {
|
| 174 |
+
"content": "<|file_sep|>",
|
| 175 |
+
"lstrip": false,
|
| 176 |
+
"normalized": false,
|
| 177 |
+
"rstrip": false,
|
| 178 |
+
"single_word": false,
|
| 179 |
+
"special": false
|
| 180 |
+
},
|
| 181 |
+
"151665": {
|
| 182 |
+
"content": "<tool_response>",
|
| 183 |
+
"lstrip": false,
|
| 184 |
+
"normalized": false,
|
| 185 |
+
"rstrip": false,
|
| 186 |
+
"single_word": false,
|
| 187 |
+
"special": false
|
| 188 |
+
},
|
| 189 |
+
"151666": {
|
| 190 |
+
"content": "</tool_response>",
|
| 191 |
+
"lstrip": false,
|
| 192 |
+
"normalized": false,
|
| 193 |
+
"rstrip": false,
|
| 194 |
+
"single_word": false,
|
| 195 |
+
"special": false
|
| 196 |
+
},
|
| 197 |
+
"151667": {
|
| 198 |
+
"content": "<think>",
|
| 199 |
+
"lstrip": false,
|
| 200 |
+
"normalized": false,
|
| 201 |
+
"rstrip": false,
|
| 202 |
+
"single_word": false,
|
| 203 |
+
"special": false
|
| 204 |
+
},
|
| 205 |
+
"151668": {
|
| 206 |
+
"content": "</think>",
|
| 207 |
+
"lstrip": false,
|
| 208 |
+
"normalized": false,
|
| 209 |
+
"rstrip": false,
|
| 210 |
+
"single_word": false,
|
| 211 |
+
"special": false
|
| 212 |
+
},
|
| 213 |
+
"151669": {
|
| 214 |
+
"content": "<tool_calls>",
|
| 215 |
+
"lstrip": false,
|
| 216 |
+
"normalized": false,
|
| 217 |
+
"rstrip": false,
|
| 218 |
+
"single_word": false,
|
| 219 |
+
"special": true
|
| 220 |
+
},
|
| 221 |
+
"151670": {
|
| 222 |
+
"content": "</tool_calls>",
|
| 223 |
+
"lstrip": false,
|
| 224 |
+
"normalized": false,
|
| 225 |
+
"rstrip": false,
|
| 226 |
+
"single_word": false,
|
| 227 |
+
"special": true
|
| 228 |
+
},
|
| 229 |
+
"151671": {
|
| 230 |
+
"content": "<|EOT|>",
|
| 231 |
+
"lstrip": false,
|
| 232 |
+
"normalized": false,
|
| 233 |
+
"rstrip": false,
|
| 234 |
+
"single_word": false,
|
| 235 |
+
"special": true
|
| 236 |
+
},
|
| 237 |
+
"151672": {
|
| 238 |
+
"content": "<|BOT|>",
|
| 239 |
+
"lstrip": false,
|
| 240 |
+
"normalized": false,
|
| 241 |
+
"rstrip": false,
|
| 242 |
+
"single_word": false,
|
| 243 |
+
"special": true
|
| 244 |
+
},
|
| 245 |
+
"151673": {
|
| 246 |
+
"content": "<|CALL_START|>",
|
| 247 |
+
"lstrip": false,
|
| 248 |
+
"normalized": false,
|
| 249 |
+
"rstrip": false,
|
| 250 |
+
"single_word": false,
|
| 251 |
+
"special": true
|
| 252 |
+
},
|
| 253 |
+
"151674": {
|
| 254 |
+
"content": "<|CALL_END|>",
|
| 255 |
+
"lstrip": false,
|
| 256 |
+
"normalized": false,
|
| 257 |
+
"rstrip": false,
|
| 258 |
+
"single_word": false,
|
| 259 |
+
"special": true
|
| 260 |
+
},
|
| 261 |
+
"151675": {
|
| 262 |
+
"content": "<|THINK_START|>",
|
| 263 |
+
"lstrip": false,
|
| 264 |
+
"normalized": false,
|
| 265 |
+
"rstrip": false,
|
| 266 |
+
"single_word": false,
|
| 267 |
+
"special": true
|
| 268 |
+
},
|
| 269 |
+
"151676": {
|
| 270 |
+
"content": "<|THINK_END|>",
|
| 271 |
+
"lstrip": false,
|
| 272 |
+
"normalized": false,
|
| 273 |
+
"rstrip": false,
|
| 274 |
+
"single_word": false,
|
| 275 |
+
"special": true
|
| 276 |
+
},
|
| 277 |
+
"151677": {
|
| 278 |
+
"content": "<|IMG_START|>",
|
| 279 |
+
"lstrip": false,
|
| 280 |
+
"normalized": false,
|
| 281 |
+
"rstrip": false,
|
| 282 |
+
"single_word": false,
|
| 283 |
+
"special": true
|
| 284 |
+
},
|
| 285 |
+
"151678": {
|
| 286 |
+
"content": "<|IMG_END|>",
|
| 287 |
+
"lstrip": false,
|
| 288 |
+
"normalized": false,
|
| 289 |
+
"rstrip": false,
|
| 290 |
+
"single_word": false,
|
| 291 |
+
"special": true
|
| 292 |
+
},
|
| 293 |
+
"151679": {
|
| 294 |
+
"content": "<im_patch>",
|
| 295 |
+
"lstrip": false,
|
| 296 |
+
"normalized": false,
|
| 297 |
+
"rstrip": false,
|
| 298 |
+
"single_word": false,
|
| 299 |
+
"special": true
|
| 300 |
+
},
|
| 301 |
+
"151680": {
|
| 302 |
+
"content": "<im_start>",
|
| 303 |
+
"lstrip": false,
|
| 304 |
+
"normalized": false,
|
| 305 |
+
"rstrip": false,
|
| 306 |
+
"single_word": false,
|
| 307 |
+
"special": true
|
| 308 |
+
},
|
| 309 |
+
"151681": {
|
| 310 |
+
"content": "<im_end>",
|
| 311 |
+
"lstrip": false,
|
| 312 |
+
"normalized": false,
|
| 313 |
+
"rstrip": false,
|
| 314 |
+
"single_word": false,
|
| 315 |
+
"special": true
|
| 316 |
+
},
|
| 317 |
+
"151682": {
|
| 318 |
+
"content": "<dream>",
|
| 319 |
+
"lstrip": false,
|
| 320 |
+
"normalized": false,
|
| 321 |
+
"rstrip": false,
|
| 322 |
+
"single_word": false,
|
| 323 |
+
"special": true
|
| 324 |
+
},
|
| 325 |
+
"151683": {
|
| 326 |
+
"content": "<dream_start>",
|
| 327 |
+
"lstrip": false,
|
| 328 |
+
"normalized": false,
|
| 329 |
+
"rstrip": false,
|
| 330 |
+
"single_word": false,
|
| 331 |
+
"special": true
|
| 332 |
+
},
|
| 333 |
+
"151684": {
|
| 334 |
+
"content": "<dream_end>",
|
| 335 |
+
"lstrip": false,
|
| 336 |
+
"normalized": false,
|
| 337 |
+
"rstrip": false,
|
| 338 |
+
"single_word": false,
|
| 339 |
+
"special": true
|
| 340 |
+
},
|
| 341 |
+
"151685": {
|
| 342 |
+
"content": "<|MASK_1e69f|>",
|
| 343 |
+
"lstrip": false,
|
| 344 |
+
"normalized": false,
|
| 345 |
+
"rstrip": false,
|
| 346 |
+
"single_word": false,
|
| 347 |
+
"special": true
|
| 348 |
+
},
|
| 349 |
+
"151686": {
|
| 350 |
+
"content": "<|UNMASK_1e69f|>",
|
| 351 |
+
"lstrip": false,
|
| 352 |
+
"normalized": false,
|
| 353 |
+
"rstrip": false,
|
| 354 |
+
"single_word": false,
|
| 355 |
+
"special": true
|
| 356 |
+
},
|
| 357 |
+
"151687": {
|
| 358 |
+
"content": "<video_start>",
|
| 359 |
+
"lstrip": false,
|
| 360 |
+
"normalized": false,
|
| 361 |
+
"rstrip": false,
|
| 362 |
+
"single_word": false,
|
| 363 |
+
"special": true
|
| 364 |
+
},
|
| 365 |
+
"151688": {
|
| 366 |
+
"content": "<video_end>",
|
| 367 |
+
"lstrip": false,
|
| 368 |
+
"normalized": false,
|
| 369 |
+
"rstrip": false,
|
| 370 |
+
"single_word": false,
|
| 371 |
+
"special": true
|
| 372 |
+
},
|
| 373 |
+
"151689": {
|
| 374 |
+
"content": "<patch_start>",
|
| 375 |
+
"lstrip": false,
|
| 376 |
+
"normalized": false,
|
| 377 |
+
"rstrip": false,
|
| 378 |
+
"single_word": false,
|
| 379 |
+
"special": true
|
| 380 |
+
},
|
| 381 |
+
"151690": {
|
| 382 |
+
"content": "<patch_end>",
|
| 383 |
+
"lstrip": false,
|
| 384 |
+
"normalized": false,
|
| 385 |
+
"rstrip": false,
|
| 386 |
+
"single_word": false,
|
| 387 |
+
"special": true
|
| 388 |
+
},
|
| 389 |
+
"151691": {
|
| 390 |
+
"content": "<patch_newline>",
|
| 391 |
+
"lstrip": false,
|
| 392 |
+
"normalized": false,
|
| 393 |
+
"rstrip": false,
|
| 394 |
+
"single_word": false,
|
| 395 |
+
"special": true
|
| 396 |
+
}
|
| 397 |
+
},
|
| 398 |
+
"additional_special_tokens": [
|
| 399 |
+
"<|im_start|>",
|
| 400 |
+
"<|im_end|>",
|
| 401 |
+
"<|object_ref_start|>",
|
| 402 |
+
"<|object_ref_end|>",
|
| 403 |
+
"<|box_start|>",
|
| 404 |
+
"<|box_end|>",
|
| 405 |
+
"<|quad_start|>",
|
| 406 |
+
"<|quad_end|>",
|
| 407 |
+
"<|vision_start|>",
|
| 408 |
+
"<|vision_end|>",
|
| 409 |
+
"<|vision_pad|>",
|
| 410 |
+
"<|image_pad|>",
|
| 411 |
+
"<|video_pad|>",
|
| 412 |
+
"<tool_calls>",
|
| 413 |
+
"</tool_calls>",
|
| 414 |
+
"<|EOT|>",
|
| 415 |
+
"<|BOT|>",
|
| 416 |
+
"<|CALL_START|>",
|
| 417 |
+
"<|CALL_END|>",
|
| 418 |
+
"<|THINK_START|>",
|
| 419 |
+
"<|THINK_END|>",
|
| 420 |
+
"<|IMG_START|>",
|
| 421 |
+
"<|IMG_END|>",
|
| 422 |
+
"<im_patch>",
|
| 423 |
+
"<im_start>",
|
| 424 |
+
"<im_end>",
|
| 425 |
+
"<dream>",
|
| 426 |
+
"<dream_start>",
|
| 427 |
+
"<dream_end>",
|
| 428 |
+
"<|MASK_1e69f|>",
|
| 429 |
+
"<|UNMASK_1e69f|>",
|
| 430 |
+
"<video_start>",
|
| 431 |
+
"<video_end>",
|
| 432 |
+
"<patch_start>",
|
| 433 |
+
"<patch_end>",
|
| 434 |
+
"<patch_newline>"
|
| 435 |
+
],
|
| 436 |
+
"bos_token": null,
|
| 437 |
+
"clean_up_tokenization_spaces": false,
|
| 438 |
+
"eos_token": "<|im_end|>",
|
| 439 |
+
"errors": "replace",
|
| 440 |
+
"extra_special_tokens": {},
|
| 441 |
+
"model_max_length": 131072,
|
| 442 |
+
"p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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Literal, Optional, Tuple, Union
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from einops import rearrange, repeat
|
| 7 |
+
from transformers.activations import ACT2FN
|
| 8 |
+
|
| 9 |
+
from .configuration_step_vl import StepRoboticsVisionEncoderConfig
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def rotate_half(x: torch.Tensor) -> torch.Tensor:
|
| 13 |
+
"""Rotate last dimension halves (used by RoPE)."""
|
| 14 |
+
x = rearrange(x, "... (d r) -> ... d r", r=2)
|
| 15 |
+
x1, x2 = x.unbind(dim=-1)
|
| 16 |
+
x = torch.stack((-x2, x1), dim=-1)
|
| 17 |
+
return rearrange(x, "... d r -> ... (d r)")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def apply_rotary_emb(freqs: torch.Tensor,
|
| 21 |
+
t: torch.Tensor,
|
| 22 |
+
start_index: int = 0,
|
| 23 |
+
scale: float = 1.0,
|
| 24 |
+
seq_dim: int = -2) -> torch.Tensor:
|
| 25 |
+
"""Apply 2D rotary embeddings to queries / keys."""
|
| 26 |
+
dtype = t.dtype
|
| 27 |
+
|
| 28 |
+
if t.ndim == 3:
|
| 29 |
+
seq_len = t.shape[seq_dim]
|
| 30 |
+
freqs = freqs[-seq_len:]
|
| 31 |
+
|
| 32 |
+
rot_dim = freqs.shape[-1]
|
| 33 |
+
end_index = start_index + rot_dim
|
| 34 |
+
assert rot_dim <= t.shape[-1], (
|
| 35 |
+
f"feature dimension {t.shape[-1]} is too small for rot_dim {rot_dim}")
|
| 36 |
+
|
| 37 |
+
t_left, t, t_right = (
|
| 38 |
+
t[..., :start_index],
|
| 39 |
+
t[..., start_index:end_index],
|
| 40 |
+
t[..., end_index:],
|
| 41 |
+
)
|
| 42 |
+
t = (t * freqs.cos() * scale) + (rotate_half(t) * freqs.sin() * scale)
|
| 43 |
+
out = torch.cat((t_left, t, t_right), dim=-1)
|
| 44 |
+
return out.type(dtype)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class EncoderRope2D(nn.Module):
|
| 48 |
+
"""Cacheable 2D rotary positional embedding."""
|
| 49 |
+
|
| 50 |
+
def __init__(
|
| 51 |
+
self,
|
| 52 |
+
dim: int,
|
| 53 |
+
max_grid_height: int,
|
| 54 |
+
max_grid_width: int,
|
| 55 |
+
use_cls_token: bool = False,
|
| 56 |
+
theta: Union[int, float] = 10000,
|
| 57 |
+
max_freq: int = 10,
|
| 58 |
+
num_freqs: int = 1,
|
| 59 |
+
theta_rescale_factor: float = 1.0,
|
| 60 |
+
):
|
| 61 |
+
super().__init__()
|
| 62 |
+
self.dim = dim
|
| 63 |
+
self.max_grid_height = max_grid_height
|
| 64 |
+
self.max_grid_width = max_grid_width
|
| 65 |
+
self.use_cls_token = use_cls_token
|
| 66 |
+
self.theta = theta * theta_rescale_factor**(dim / (dim - 2))
|
| 67 |
+
self.max_freq = max_freq
|
| 68 |
+
self.num_freqs = num_freqs
|
| 69 |
+
cache = self._compute_2d_freqs()
|
| 70 |
+
self.register_buffer("freqs_cache", cache, persistent=False)
|
| 71 |
+
|
| 72 |
+
def _compute_inv_freq(self, base: Union[int, float],
|
| 73 |
+
dim: int) -> torch.Tensor:
|
| 74 |
+
|
| 75 |
+
freqs = 1.0 / (base**(
|
| 76 |
+
torch.arange(0, dim, 2)[:(dim // 2)].float() / dim))
|
| 77 |
+
return freqs
|
| 78 |
+
|
| 79 |
+
def _compute_freqs(self, t: torch.Tensor, inv_freq: torch.Tensor):
|
| 80 |
+
freqs = torch.einsum("..., f -> ... f", t.type(inv_freq.dtype),
|
| 81 |
+
inv_freq)
|
| 82 |
+
freqs = repeat(freqs, "... n -> ... (n r)", r=2)
|
| 83 |
+
return freqs
|
| 84 |
+
|
| 85 |
+
def _compute_2d_freqs(self) -> torch.Tensor:
|
| 86 |
+
grid_h_range = torch.arange(self.max_grid_height, dtype=torch.float)
|
| 87 |
+
grid_w_range = torch.arange(self.max_grid_width, dtype=torch.float)
|
| 88 |
+
if self.use_cls_token:
|
| 89 |
+
grid_h_range += 1
|
| 90 |
+
grid_w_range += 1
|
| 91 |
+
inv_freq = self._compute_inv_freq(self.theta, self.dim // 2)
|
| 92 |
+
freqs_h = self._compute_freqs(grid_h_range, inv_freq)[:, None].expand(
|
| 93 |
+
self.max_grid_height, self.max_grid_width, -1)
|
| 94 |
+
freqs_w = self._compute_freqs(grid_w_range, inv_freq)[None, :].expand(
|
| 95 |
+
self.max_grid_height, self.max_grid_width, -1)
|
| 96 |
+
freqs = torch.cat([freqs_w, freqs_h], dim=-1).reshape(
|
| 97 |
+
self.max_grid_height * self.max_grid_width, -1)
|
| 98 |
+
if self.use_cls_token:
|
| 99 |
+
freqs = torch.cat([torch.zeros(1, freqs.shape[-1]), freqs], dim=0)
|
| 100 |
+
freqs = freqs[None, None, ...]
|
| 101 |
+
return freqs
|
| 102 |
+
|
| 103 |
+
def forward(self, q: torch.Tensor, k: torch.Tensor,
|
| 104 |
+
grid_hw: tuple[int, int]):
|
| 105 |
+
# If grid matches cached shape we reuse directly to avoid recomputation.
|
| 106 |
+
if grid_hw[0] != self.max_grid_height or grid_hw[1] != self.max_grid_width:
|
| 107 |
+
rows = torch.arange(grid_hw[0], device=q.device).view(-1, 1)
|
| 108 |
+
cols = torch.arange(grid_hw[1], device=q.device).view(1, -1)
|
| 109 |
+
positions = (rows * self.max_grid_width + cols).reshape(-1).to(
|
| 110 |
+
torch.long)
|
| 111 |
+
if self.use_cls_token:
|
| 112 |
+
positions = torch.cat(
|
| 113 |
+
[torch.zeros(1, device=q.device), positions + 1], dim=0)
|
| 114 |
+
freqs = self.freqs_cache.index_select(2, positions)
|
| 115 |
+
else:
|
| 116 |
+
freqs = self.freqs_cache
|
| 117 |
+
q = apply_rotary_emb(freqs, q)
|
| 118 |
+
k = apply_rotary_emb(freqs, k)
|
| 119 |
+
return q, k
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class EncoderLayerScale(nn.Module):
|
| 123 |
+
"""Per-channel residual scaling used when ls_init_value is set."""
|
| 124 |
+
|
| 125 |
+
def __init__(self, dim: int, init_values: float):
|
| 126 |
+
super().__init__()
|
| 127 |
+
self.gamma = nn.Parameter(torch.full((dim,), init_values))
|
| 128 |
+
|
| 129 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: # (B, L, D)
|
| 130 |
+
return hidden_states * self.gamma
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class EncoderMLP(nn.Module):
|
| 134 |
+
"""Feed-forward network used inside each transformer block."""
|
| 135 |
+
|
| 136 |
+
def __init__(self, hidden_size: int, intermediate_size: int,
|
| 137 |
+
hidden_act: str):
|
| 138 |
+
super().__init__()
|
| 139 |
+
self.c_fc = nn.Linear(hidden_size, intermediate_size, bias=True)
|
| 140 |
+
self.act_fn = ACT2FN[hidden_act]
|
| 141 |
+
self.c_proj = nn.Linear(intermediate_size, hidden_size, bias=True)
|
| 142 |
+
|
| 143 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 144 |
+
|
| 145 |
+
hidden_states = self.c_proj(self.act_fn(self.c_fc(hidden_states)))
|
| 146 |
+
return hidden_states
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class EncoderVisionAttention(nn.Module):
|
| 150 |
+
"""Multi-head self attention with optional 2D RoPE."""
|
| 151 |
+
|
| 152 |
+
def __init__(
|
| 153 |
+
self,
|
| 154 |
+
hidden_size: int,
|
| 155 |
+
num_heads: int,
|
| 156 |
+
max_grid_height: int,
|
| 157 |
+
max_grid_width: int,
|
| 158 |
+
use_cls_token: bool = False,
|
| 159 |
+
use_rope2d: bool = True,
|
| 160 |
+
rope_theta: Union[int, float] = 10000,
|
| 161 |
+
rope_max_freq: int = 10,
|
| 162 |
+
rope_num_freqs: int = 1,
|
| 163 |
+
rope_theta_rescale_factor: float = 1.0,
|
| 164 |
+
rope_freqs_for: Literal["lang", "pixel", "constant"] = "lang",
|
| 165 |
+
):
|
| 166 |
+
super().__init__()
|
| 167 |
+
if hidden_size % num_heads != 0:
|
| 168 |
+
raise ValueError(
|
| 169 |
+
f"hidden_size ({hidden_size}) must be divisible by num_heads ({num_heads})."
|
| 170 |
+
)
|
| 171 |
+
self.num_heads = num_heads
|
| 172 |
+
self.head_dim = hidden_size // num_heads
|
| 173 |
+
self.scale = self.head_dim**-0.5
|
| 174 |
+
self.in_proj_weight = nn.Parameter(torch.zeros(hidden_size * 3, hidden_size))
|
| 175 |
+
self.in_proj_bias = nn.Parameter(torch.zeros(hidden_size * 3))
|
| 176 |
+
self.out_proj = nn.Linear(hidden_size, hidden_size, bias=True)
|
| 177 |
+
|
| 178 |
+
self.rope = None
|
| 179 |
+
if use_rope2d:
|
| 180 |
+
self.rope = EncoderRope2D(
|
| 181 |
+
dim=self.head_dim,
|
| 182 |
+
max_grid_height=max_grid_height,
|
| 183 |
+
max_grid_width=max_grid_width,
|
| 184 |
+
use_cls_token=use_cls_token,
|
| 185 |
+
theta=rope_theta,
|
| 186 |
+
max_freq=rope_max_freq,
|
| 187 |
+
num_freqs=rope_num_freqs,
|
| 188 |
+
theta_rescale_factor=rope_theta_rescale_factor,
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
def forward(self, hidden_states: torch.Tensor, grid_hw: tuple[int, int]) -> torch.Tensor:
|
| 192 |
+
bsz, seq_len, _ = hidden_states.shape
|
| 193 |
+
qkv = F.linear(
|
| 194 |
+
hidden_states,
|
| 195 |
+
self.in_proj_weight,
|
| 196 |
+
self.in_proj_bias,
|
| 197 |
+
)
|
| 198 |
+
q, k, v = qkv.chunk(3, dim=-1)
|
| 199 |
+
|
| 200 |
+
q = q.view(bsz, seq_len, self.num_heads,
|
| 201 |
+
self.head_dim).transpose(1, 2)
|
| 202 |
+
k = k.view(bsz, seq_len, self.num_heads,
|
| 203 |
+
self.head_dim).transpose(1, 2)
|
| 204 |
+
if self.rope is not None:
|
| 205 |
+
q, k = self.rope(q, k, grid_hw=grid_hw)
|
| 206 |
+
v = v.view(bsz, seq_len, self.num_heads,
|
| 207 |
+
self.head_dim).transpose(1, 2)
|
| 208 |
+
|
| 209 |
+
attn_output = F.scaled_dot_product_attention(
|
| 210 |
+
q, k, v, is_causal=False, scale=self.scale)
|
| 211 |
+
attn_output = attn_output.transpose(1, 2).reshape(
|
| 212 |
+
bsz, seq_len, self.num_heads * self.head_dim)
|
| 213 |
+
return self.out_proj(attn_output)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
class EncoderVisionBlock(nn.Module):
|
| 217 |
+
"""A single Vision Transformer block (self-attention + MLP)."""
|
| 218 |
+
|
| 219 |
+
def __init__(
|
| 220 |
+
self,
|
| 221 |
+
hidden_size: int,
|
| 222 |
+
num_heads: int,
|
| 223 |
+
mlp_ratio: float,
|
| 224 |
+
hidden_act: str,
|
| 225 |
+
layer_norm_eps: float,
|
| 226 |
+
ls_init_value: Optional[float] = None,
|
| 227 |
+
max_grid_height: Optional[int] = None,
|
| 228 |
+
max_grid_width: Optional[int] = None,
|
| 229 |
+
use_cls_token: bool = False,
|
| 230 |
+
use_rope2d: bool = True,
|
| 231 |
+
rope_kwargs: Optional[dict] = None,
|
| 232 |
+
):
|
| 233 |
+
super().__init__()
|
| 234 |
+
rope_kwargs = rope_kwargs or {}
|
| 235 |
+
self.attn = EncoderVisionAttention(
|
| 236 |
+
hidden_size,
|
| 237 |
+
num_heads,
|
| 238 |
+
max_grid_height=max_grid_height,
|
| 239 |
+
max_grid_width=max_grid_width,
|
| 240 |
+
use_cls_token=use_cls_token,
|
| 241 |
+
use_rope2d=use_rope2d,
|
| 242 |
+
**rope_kwargs,
|
| 243 |
+
)
|
| 244 |
+
self.ln_1 = nn.LayerNorm(hidden_size, eps=layer_norm_eps)
|
| 245 |
+
self.ln_2 = nn.LayerNorm(hidden_size, eps=layer_norm_eps)
|
| 246 |
+
|
| 247 |
+
intermediate = int(hidden_size * mlp_ratio)
|
| 248 |
+
self.mlp = EncoderMLP(hidden_size, intermediate, hidden_act)
|
| 249 |
+
|
| 250 |
+
self.ls_1 = EncoderLayerScale(hidden_size, ls_init_value)
|
| 251 |
+
self.ls_2 = EncoderLayerScale(hidden_size, ls_init_value)
|
| 252 |
+
|
| 253 |
+
def forward(self, hidden_states: torch.Tensor,
|
| 254 |
+
grid_hw: tuple[int, int]) -> torch.Tensor:
|
| 255 |
+
# breakpoint()
|
| 256 |
+
residual = hidden_states
|
| 257 |
+
hidden_states = self.ln_1(hidden_states)
|
| 258 |
+
hidden_states = self.attn(hidden_states, grid_hw=grid_hw)
|
| 259 |
+
hidden_states = residual + self.ls_1(hidden_states)
|
| 260 |
+
|
| 261 |
+
residual = hidden_states
|
| 262 |
+
hidden_states = self.ln_2(hidden_states)
|
| 263 |
+
hidden_states = self.mlp(hidden_states)
|
| 264 |
+
hidden_states = residual + self.ls_2(hidden_states)
|
| 265 |
+
return hidden_states
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
class EncoderVisionTransformer(nn.Module):
|
| 269 |
+
"""Stack of encoder blocks parameterised by Step35VisionEncoderConfig."""
|
| 270 |
+
|
| 271 |
+
def __init__(
|
| 272 |
+
self,
|
| 273 |
+
embed_dim: int,
|
| 274 |
+
depth: int,
|
| 275 |
+
num_heads: int,
|
| 276 |
+
mlp_ratio: float,
|
| 277 |
+
hidden_act: str,
|
| 278 |
+
layer_norm_eps: float,
|
| 279 |
+
ls_init_value: Optional[float] = None,
|
| 280 |
+
max_grid_height: Optional[int] = None,
|
| 281 |
+
max_grid_width: Optional[int] = None,
|
| 282 |
+
use_cls_token: bool = False,
|
| 283 |
+
use_rope2d: bool = True,
|
| 284 |
+
rope_kwargs: Optional[dict] = None,
|
| 285 |
+
):
|
| 286 |
+
super().__init__()
|
| 287 |
+
self.layers = depth
|
| 288 |
+
rope_kwargs = rope_kwargs or {}
|
| 289 |
+
self.resblocks = nn.ModuleList([
|
| 290 |
+
EncoderVisionBlock(embed_dim, num_heads, mlp_ratio, hidden_act,
|
| 291 |
+
layer_norm_eps,
|
| 292 |
+
max_grid_height=max_grid_height,
|
| 293 |
+
max_grid_width=max_grid_width,
|
| 294 |
+
use_cls_token=use_cls_token,
|
| 295 |
+
use_rope2d=use_rope2d,
|
| 296 |
+
ls_init_value=ls_init_value,
|
| 297 |
+
rope_kwargs=rope_kwargs)
|
| 298 |
+
for _ in range(depth)
|
| 299 |
+
])
|
| 300 |
+
|
| 301 |
+
def forward(self,
|
| 302 |
+
hidden_states: torch.Tensor,
|
| 303 |
+
grid_hw: tuple[int, int]) -> torch.Tensor:
|
| 304 |
+
for block in self.resblocks:
|
| 305 |
+
hidden_states = block(hidden_states, grid_hw=grid_hw)
|
| 306 |
+
return hidden_states
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
class StepRoboticsVisionEncoder(nn.Module):
|
| 310 |
+
"""
|
| 311 |
+
Vision encoder built from StepRoboticsVisionEncoderConfig.
|
| 312 |
+
|
| 313 |
+
The encoder performs patch embedding followed by a stack of transformer
|
| 314 |
+
blocks. Only the config fields defined in StepRoboticsVisionEncoderConfig (and
|
| 315 |
+
StepRoboticVLConfig.vision_config) are expected.
|
| 316 |
+
"""
|
| 317 |
+
|
| 318 |
+
def __init__(self, config: StepRoboticsVisionEncoderConfig):
|
| 319 |
+
super().__init__()
|
| 320 |
+
self.config = config
|
| 321 |
+
|
| 322 |
+
# Align commonly used attributes so downstream code (e.g. StepRoboticVL)
|
| 323 |
+
# can access them without extra renaming.
|
| 324 |
+
self.hidden_size = config.width
|
| 325 |
+
self.num_heads = config.heads
|
| 326 |
+
self.num_hidden_layers = config.layers
|
| 327 |
+
self.patch_size = config.patch_size
|
| 328 |
+
self.image_size = config.image_size
|
| 329 |
+
self.use_cls_token = getattr(config, "use_cls_token", False)
|
| 330 |
+
self.use_rope2d = getattr(config, "use_rope2d", True)
|
| 331 |
+
self.use_abs_posemb = getattr(config, "use_abs_posemb", True)
|
| 332 |
+
self.layer_norm_eps = config.layer_norm_eps
|
| 333 |
+
self.mlp_ratio = getattr(config, "mlp_ratio", 8960 / 1536)
|
| 334 |
+
self.ls_init_value = getattr(config, "ls_init_value", None)
|
| 335 |
+
self.hidden_act = config.hidden_act
|
| 336 |
+
self.use_ln_pre = getattr(config, "use_ln_pre", False)
|
| 337 |
+
self.use_ln_post = getattr(config, "use_ln_post", True)
|
| 338 |
+
|
| 339 |
+
# Patch embedding.
|
| 340 |
+
self.conv1 = nn.Conv2d(in_channels=config.num_channels,
|
| 341 |
+
out_channels=self.hidden_size,
|
| 342 |
+
kernel_size=self.patch_size,
|
| 343 |
+
stride=self.patch_size,
|
| 344 |
+
bias=False)
|
| 345 |
+
|
| 346 |
+
self.ln_pre = nn.LayerNorm(self.hidden_size, eps=self.layer_norm_eps) if self.use_ln_pre else nn.Identity()
|
| 347 |
+
self.ln_post = nn.LayerNorm(self.hidden_size, eps=self.layer_norm_eps) if self.use_ln_post else nn.Identity()
|
| 348 |
+
|
| 349 |
+
grid_size = self.image_size // self.patch_size
|
| 350 |
+
self.base_grid = (grid_size, grid_size)
|
| 351 |
+
|
| 352 |
+
if self.use_cls_token:
|
| 353 |
+
self.class_embedding = nn.Parameter(
|
| 354 |
+
torch.randn(self.hidden_size) * (self.hidden_size**-0.5))
|
| 355 |
+
else:
|
| 356 |
+
self.class_embedding = None
|
| 357 |
+
|
| 358 |
+
if self.use_abs_posemb:
|
| 359 |
+
self.posemb_grid_size = self.image_size // self.patch_size
|
| 360 |
+
self.positional_embedding = nn.Parameter(
|
| 361 |
+
(self.hidden_size**-0.5) * torch.randn(
|
| 362 |
+
int(self.use_cls_token) + self.posemb_grid_size**2,
|
| 363 |
+
self.hidden_size,
|
| 364 |
+
))
|
| 365 |
+
|
| 366 |
+
self.transformer = EncoderVisionTransformer(
|
| 367 |
+
embed_dim=self.hidden_size,
|
| 368 |
+
depth=self.num_hidden_layers,
|
| 369 |
+
num_heads=self.num_heads,
|
| 370 |
+
mlp_ratio=self.mlp_ratio,
|
| 371 |
+
hidden_act=self.hidden_act,
|
| 372 |
+
layer_norm_eps=self.layer_norm_eps,
|
| 373 |
+
ls_init_value=self.ls_init_value,
|
| 374 |
+
max_grid_height=self.base_grid[0],
|
| 375 |
+
max_grid_width=self.base_grid[1],
|
| 376 |
+
use_cls_token=self.use_cls_token,
|
| 377 |
+
use_rope2d=self.use_rope2d,
|
| 378 |
+
rope_kwargs={
|
| 379 |
+
"rope_theta": getattr(config, "rope_theta", 10000),
|
| 380 |
+
"rope_max_freq": getattr(config, "rope_max_freq", 10),
|
| 381 |
+
"rope_num_freqs": getattr(config, "rope_num_freqs", 1),
|
| 382 |
+
"rope_theta_rescale_factor":
|
| 383 |
+
getattr(config, "rope_theta_rescale_factor", 1.0),
|
| 384 |
+
"rope_freqs_for": getattr(config, "rope_freqs_for", "lang"),
|
| 385 |
+
},
|
| 386 |
+
)
|
| 387 |
+
self.vit_downsampler1 = nn.Conv2d(self.hidden_size,
|
| 388 |
+
self.hidden_size * 2,
|
| 389 |
+
kernel_size=3,
|
| 390 |
+
stride=2,
|
| 391 |
+
padding=1)
|
| 392 |
+
self.vit_downsampler2 = nn.Conv2d(self.hidden_size * 2,
|
| 393 |
+
self.hidden_size * 4,
|
| 394 |
+
kernel_size=3,
|
| 395 |
+
stride=2,
|
| 396 |
+
padding=1)
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def sample_abs_posemb(self, grid_h: int, grid_w: int):
|
| 400 |
+
if self.posemb_grid_size == grid_h and self.posemb_grid_size == grid_w:
|
| 401 |
+
return self.positional_embedding[None, ...]
|
| 402 |
+
|
| 403 |
+
pos_embed = self.positional_embedding
|
| 404 |
+
if self.use_cls_token:
|
| 405 |
+
cls_token_embed, pos_embed = pos_embed[:1], pos_embed[1:]
|
| 406 |
+
|
| 407 |
+
pos_embed = (pos_embed.reshape(1, self.posemb_grid_size,
|
| 408 |
+
self.posemb_grid_size,
|
| 409 |
+
-1).permute(0, 3, 1, 2).contiguous())
|
| 410 |
+
pos_embed = F.interpolate(pos_embed,
|
| 411 |
+
size=(grid_h, grid_w),
|
| 412 |
+
mode="bilinear",
|
| 413 |
+
align_corners=False)
|
| 414 |
+
pos_embed = pos_embed.permute(0, 2, 3, 1).reshape(-1, self.hidden_size)
|
| 415 |
+
|
| 416 |
+
if self.use_cls_token:
|
| 417 |
+
pos_embed = torch.cat([cls_token_embed, pos_embed], dim=0)
|
| 418 |
+
|
| 419 |
+
return pos_embed[None, ...]
|
| 420 |
+
|
| 421 |
+
def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
|
| 422 |
+
"""
|
| 423 |
+
Args:
|
| 424 |
+
pixel_values: Image tensor of shape (B, C, H, W).
|
| 425 |
+
layer_idx: Negative indices stop after a given block (e.g., -1 uses all blocks).
|
| 426 |
+
strip_cls_token: If True and cls token is used, remove it from output.
|
| 427 |
+
"""
|
| 428 |
+
bsz, _, height, width = pixel_values.shape
|
| 429 |
+
grid_h, grid_w = height // self.patch_size, width // self.patch_size
|
| 430 |
+
|
| 431 |
+
hidden_state = self.conv1(pixel_values) # (B, D, Gh, Gw)
|
| 432 |
+
hidden_state = hidden_state.flatten(2).transpose(1, 2) # (B, Gh*Gw, D)
|
| 433 |
+
|
| 434 |
+
if self.use_cls_token:
|
| 435 |
+
cls_token = self.class_embedding.view(1, 1,
|
| 436 |
+
-1).expand(bsz, -1, -1)
|
| 437 |
+
hidden_state = torch.cat([cls_token, hidden_state], dim=1)
|
| 438 |
+
|
| 439 |
+
if self.use_abs_posemb:
|
| 440 |
+
pos_emb = self.sample_abs_posemb(grid_h, grid_w)
|
| 441 |
+
hidden_state = hidden_state + pos_emb
|
| 442 |
+
hidden_state = self.ln_pre(hidden_state)
|
| 443 |
+
hidden_state = self.transformer(hidden_state, grid_hw=(grid_h, grid_w))
|
| 444 |
+
|
| 445 |
+
if self.use_ln_post:
|
| 446 |
+
hidden_state = self.ln_post(hidden_state)
|
| 447 |
+
|
| 448 |
+
if self.use_cls_token:
|
| 449 |
+
hidden_state = hidden_state[:, 1:, :]
|
| 450 |
+
|
| 451 |
+
return hidden_state
|
vocab.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|