File size: 3,670 Bytes
cb16f2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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),
    }