def create_model(source_model_id: str, source_revision: str, save_folder: str) -> str: import json from pathlib import Path import torch from huggingface_hub import hf_hub_download from transformers import AutoConfig, AutoModel folder = Path(save_folder) folder.mkdir(parents=True, exist_ok=True) for name in ( "configuration_mistral_contrastive.py", "modeling_mistral_contrastive.py", "image_processing_mistral_contrastive.py", "image_transforms.py", "preprocessor_config.json", "tokenizer.json", "tokenizer_config.json", "special_tokens_map.json", "LICENSE", ): (folder / name).write_bytes(Path(hf_hub_download(source_model_id, name, revision=source_revision)).read_bytes()) config = json.loads(Path(hf_hub_download(source_model_id, "config.json", revision=source_revision)).read_text()) # 64-wide residual streams keep the 131,072-row embedding near 17 MB while # preserving heads*head_dim == width in both towers and the 4-layer, # 64-wide temporal encoder. config.update( text_dim=64, text_num_hidden_layers=4, text_num_attention_heads=2, text_head_dim=32, text_intermediate_size=256, vision_dim=64, vision_num_hidden_layers=4, vision_num_attention_heads=2, vision_head_dim=32, vision_intermediate_size=256, temporal_num_attention_heads=2, ) (folder / "config.json").write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8") model_config = AutoConfig.from_pretrained(folder, trust_remote_code=True) torch.manual_seed(42) torch.set_default_dtype(torch.bfloat16) model = AutoModel.from_config(model_config, trust_remote_code=True) torch.set_default_dtype(torch.float32) # Deterministic, active weights; keep the FP32 logit scale at its source value. with torch.no_grad(): for name, parameter in sorted(model.named_parameters()): if name == "logit_scale" or parameter.ndim == 0: continue if name.endswith(".bias"): parameter.zero_() elif name.endswith("weight") and "norm" in name: parameter.fill_(1.0) else: parameter.normal_(0.0, 0.02) model.save_pretrained(folder, safe_serialization=True) # save_pretrained rewrites config.json; restore the shrunk source document. (folder / "config.json").write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8") print(model) return str(model) if __name__ == "__main__": create_model( source_model_id="mistralai/Mistral-Multimodal-Embed-1B", source_revision="38fe0971eb3944a1273f429338a9cf704f223bff", save_folder="/tmp/mistral-multimodal-embed", )