Download assistant/vision-export/v2/user_script.py from T8RIN/imagetoolbox-models: direct link, hf CLI and curl.
- Browser
- Download file 3.67 kB
-
https://huggingface.co/T8RIN/imagetoolbox-models/resolve/main/assistant/vision-export/v2/user_script.py
- Command line
-
hf download hf://T8RIN/imagetoolbox-models/assistant/vision-export/v2/user_script.py
-
curl -L -o user_script.py https://huggingface.co/T8RIN/imagetoolbox-models/resolve/main/assistant/vision-export/v2/user_script.py
3.67 kB
| from pathlib import Path | |
| import torch | |
| from safetensors import safe_open | |
| from transformers import Qwen3_5Config | |
| from codes.modeling_qwen3_5 import Qwen3_5Model, Qwen3_5VisionModel | |
| def _load_base_model(model_path): | |
| source = Path(model_path) | |
| config = Qwen3_5Config.from_pretrained(source, local_files_only=True) | |
| model = Qwen3_5Model(config) | |
| state = {} | |
| for file in sorted(source.glob('*.safetensors')): | |
| with safe_open(file, framework='pt', device='cpu') as weights: | |
| for key in weights.keys(): | |
| if key.startswith('model.visual.'): | |
| state[key[len('model.'):]] = weights.get_tensor(key).float() | |
| elif key == 'model.language_model.embed_tokens.weight': | |
| state['embed_tokens.weight'] = weights.get_tensor(key).float() | |
| result = model.load_state_dict(state, strict=False) | |
| missing = [key for key in result.missing_keys if key != 'visual.rotary_pos_emb.inv_freq'] | |
| if missing or result.unexpected_keys: | |
| raise RuntimeError(f'Invalid weights: {missing=}, {result.unexpected_keys=}') | |
| model.eval() | |
| return model | |
| def get_embedding_model(model_path=None): | |
| model = _load_base_model(model_path) | |
| model.forward = model.get_fused_input_embeddings | |
| return model | |
| def get_embedding_io_config(model_path=None): | |
| return { | |
| 'input_names': ['input_ids', 'image_features'], | |
| 'output_names': ['inputs_embeds'], | |
| 'dynamic_axes': { | |
| 'input_ids': {0: 'batch_size', 1: 'sequence_length'}, | |
| 'image_features': {0: 'num_logical_patches'}, | |
| 'inputs_embeds': {0: 'batch_size', 1: 'sequence_length'}, | |
| }, | |
| } | |
| def get_embedding_dummy_inputs(model=None): | |
| config = Qwen3_5Config.from_pretrained(model.model_path, local_files_only=True) | |
| input_ids = torch.randint(0, 10000, (1, 20), dtype=torch.int64) | |
| input_ids[0, 2] = config.vision_start_token_id | |
| input_ids[0, 3:19] = config.image_token_id | |
| input_ids[0, 19] = config.vision_end_token_id | |
| return {'input_ids': input_ids, 'image_features': torch.randn(16, config.text_config.hidden_size)} | |
| class VisionEncoder(torch.nn.Module): | |
| def __init__(self, config): | |
| super().__init__() | |
| self.visual = Qwen3_5VisionModel._from_config(config.vision_config) | |
| def forward(self, pixel_values, image_grid_thw): | |
| return self.visual(pixel_values, grid_thw=image_grid_thw) | |
| def get_vision_model(model_path=None): | |
| source = Path(model_path) | |
| config = Qwen3_5Config.from_pretrained(source, local_files_only=True) | |
| model = VisionEncoder(config) | |
| state = {} | |
| for file in sorted(source.glob('*.safetensors')): | |
| with safe_open(file, framework='pt', device='cpu') as weights: | |
| for key in weights.keys(): | |
| if key.startswith('model.visual.'): | |
| state[key[len('model.'):]] = weights.get_tensor(key).float() | |
| result = model.load_state_dict(state, strict=False) | |
| missing = [key for key in result.missing_keys if key != 'visual.rotary_pos_emb.inv_freq'] | |
| if missing or result.unexpected_keys: | |
| raise RuntimeError(f'Invalid vision weights: {missing=}, {result.unexpected_keys=}') | |
| return model.eval() | |
| def get_vision_io_config(model_path=None): | |
| return { | |
| 'input_names': ['pixel_values', 'image_grid_thw'], | |
| 'output_names': ['image_features'], | |
| 'dynamic_shapes': {'pixel_values': {0: 'num_patches'}, 'image_grid_thw': None}, | |
| } | |
| def get_vision_dummy_inputs(model=None): | |
| return { | |
| 'pixel_values': torch.randn(16 * 16, 1536), | |
| 'image_grid_thw': torch.tensor([[1, 16, 16]], dtype=torch.int64), | |
| } | |