File size: 7,716 Bytes
07d61c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# coding=utf-8
# Copyright 2025-present, the HuggingFace Inc. Team and AIRAS Inc. Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import torch
import json
from pathlib import Path
from transformers import AutoModelForCausalLM, AutoTokenizer
from ctransformers import AutoModelForCausalLM as GGUFModel
from models.sapnous import SapnousT1Config

def load_safetensors_state_dict(model_path, weight_map):
    """Load state dict from safetensors shards with custom metadata handling."""
    import safetensors
    from safetensors.torch import load_file

    state_dict = {}
    metadata = {}
    
    # Load and validate each shard
    for param_name, shard_file in weight_map['weight_map'].items():
        shard_path = os.path.join(model_path, shard_file)
        if not os.path.exists(shard_path):
            raise OSError(f"Missing weight shard: {shard_path}")
            
        try:
            # Load shard with metadata
            shard_dict = load_file(shard_path)
            shard_metadata = safetensors.safe_open(shard_path, framework="pt").metadata()
            
            if shard_metadata:
                metadata.update(shard_metadata)
            
            # Add tensors to state dict
            for key, tensor in shard_dict.items():
                if key in state_dict:
                    raise ValueError(f"Duplicate parameter {key} found in multiple shards")
                state_dict[key] = tensor
                
        except Exception as e:
            raise OSError(f"Error loading shard {shard_file}: {str(e)}")
    
    # Add metadata to state dict
    if metadata:
        state_dict['_metadata'] = metadata
    
    return state_dict
    return state_dict

def convert_to_gguf(model_path, output_path):
    # Load configuration and weight map
    config_path = os.path.join(model_path, 'config.json')
    weight_map_path = os.path.join(model_path, 'model.safetensors.index.json')
    
    if not os.path.exists(config_path):
        raise OSError(f"Missing config file: {config_path}")
    if not os.path.exists(weight_map_path):
        raise OSError(f"Missing weight map file: {weight_map_path}")
        
    with open(config_path, 'r') as f:
        config = json.load(f)
    with open(weight_map_path, 'r') as f:
        weight_map = json.load(f)
        
    # Validate weight map structure
    if 'weight_map' not in weight_map:
        raise ValueError("Invalid weight map format: missing 'weight_map' key")
    if 'metadata' not in weight_map:
        raise ValueError("Invalid weight map format: missing 'metadata' key")
    
    # Load the model and tokenizer with vision-language support
    model = AutoModelForCausalLM.from_pretrained(
        model_path,
        trust_remote_code=True,
        device_map=None,  # Disable device mapping for conversion
        torch_dtype=torch.float16,  # Use FP16 for memory efficiency
        low_cpu_mem_usage=True,  # Enable low CPU memory usage
        local_files_only=True,  # Use local files only
        ignore_mismatched_sizes=True,  # Bypass size validation
        use_safetensors=True,  # Explicitly enable safetensors
        use_auth_token=False  # Disable auth token
    )
    tokenizer = AutoTokenizer.from_pretrained(
        model_path,
        trust_remote_code=True
    )
    
    # Get model configuration
    config = model.config
    if not isinstance(config, SapnousT1Config):
        raise ValueError("Model must be a SapnousT1 model")
    
    # Save in intermediate format
    model.save_pretrained(output_path, safe_serialization=True)
    tokenizer.save_pretrained(output_path)
    
    # Convert to GGUF using custom SapnousT1 architecture settings
    gguf_model = GGUFModel.from_pretrained(
        output_path,
        model_type='sapnous_t1',  # Custom architecture type
        gpu_layers=0,  # CPU only for conversion
        config={
            'context_length': config.sliding_window,
            'attention_type': 'multihead',  # Custom attention implementation
            'num_attention_heads': config.num_attention_heads,
            'num_key_value_heads': config.num_key_value_heads,
            'hidden_size': config.hidden_size,
            'intermediate_size': config.intermediate_size,
            'max_position_embeddings': config.max_position_embeddings,
            'vocab_size': config.vocab_size,
            'num_hidden_layers': config.num_hidden_layers,
            'rms_norm_eps': config.rms_norm_eps,
            'rope_theta': config.rope_theta,
            # Vision model parameters
            'vision_config': {
                'hidden_size': config.vision_hidden_size,
                'num_hidden_layers': config.vision_layers,
                'num_attention_heads': config.vision_heads,
                'intermediate_size': config.vision_intermediate_size,
                'patch_size': config.patch_size,
                'image_size': config.image_size
            }
        }
    )
    
    print(f"Model converted and saved to {output_path}")
    return gguf_model

def convert_to_hf(gguf_path, output_path):
    """Convert GGUF model back to Hugging Face format"""
    # Load GGUF model configuration
    config_path = Path(gguf_path) / "config.json"
    with open(config_path, 'r') as f:
        gguf_config = json.load(f)
    
    # Create SapnousT1 configuration
    config = SapnousT1Config(
        vocab_size=gguf_config['vocab_size'],
        hidden_size=gguf_config['hidden_size'],
        num_hidden_layers=gguf_config['num_hidden_layers'],
        num_attention_heads=gguf_config['num_attention_heads'],
        num_key_value_heads=gguf_config['num_key_value_heads'],
        intermediate_size=gguf_config['intermediate_size'],
        max_position_embeddings=gguf_config['max_position_embeddings'],
        rms_norm_eps=gguf_config['rms_norm_eps'],
        rope_theta=gguf_config['rope_theta'],
        # Vision configuration
        vision_hidden_size=gguf_config['vision_config']['hidden_size'],
        vision_layers=gguf_config['vision_config']['num_hidden_layers'],
        vision_heads=gguf_config['vision_config']['num_attention_heads'],
        vision_intermediate_size=gguf_config['vision_config']['intermediate_size'],
        patch_size=gguf_config['vision_config']['patch_size'],
        image_size=gguf_config['vision_config']['image_size']
    )
    
    # Load GGUF model
    gguf_model = GGUFModel.from_pretrained(gguf_path)
    
    # Convert weights to HF format
    model = AutoModelForCausalLM.from_config(config)
    model.load_state_dict(gguf_model.state_dict())
    
    # Save converted model
    model.save_pretrained(output_path)
    print(f"Model converted back to Hugging Face format at {output_path}")
    return model

if __name__ == '__main__':
    model_path = os.path.dirname(os.path.abspath(__file__))
    output_path = os.path.join(model_path, 'gguf_model')
    
    if not os.path.exists(output_path):
        os.makedirs(output_path)
        
    convert_to_gguf(model_path, output_path)