{"id":17596220,"url":"https://github.com/lamm-mit/cephalo-phi-3-vision-moe","last_synced_at":"2025-04-30T06:40:34.817Z","repository":{"id":243555792,"uuid":"808809940","full_name":"lamm-mit/Cephalo-Phi-3-Vision-MoE","owner":"lamm-mit","description":null,"archived":false,"fork":false,"pushed_at":"2024-06-09T19:10:41.000Z","size":89,"stargazers_count":11,"open_issues_count":0,"forks_count":2,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-18T21:31:32.207Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/lamm-mit.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-05-31T21:45:44.000Z","updated_at":"2024-09-17T03:08:22.000Z","dependencies_parsed_at":"2024-06-09T20:55:41.164Z","dependency_job_id":"88fc0467-e3d0-4e63-a241-fbe425cfaef0","html_url":"https://github.com/lamm-mit/Cephalo-Phi-3-Vision-MoE","commit_stats":null,"previous_names":["lamm-mit/cephalo-phi-3-vision-moe"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lamm-mit%2FCephalo-Phi-3-Vision-MoE","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lamm-mit%2FCephalo-Phi-3-Vision-MoE/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lamm-mit%2FCephalo-Phi-3-Vision-MoE/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lamm-mit%2FCephalo-Phi-3-Vision-MoE/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lamm-mit","download_url":"https://codeload.github.com/lamm-mit/Cephalo-Phi-3-Vision-MoE/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251657405,"owners_count":21622813,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-22T08:24:26.774Z","updated_at":"2025-04-30T06:40:34.767Z","avatar_url":"https://github.com/lamm-mit.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"## Cephalo Mixture-of-Expert models based on Phi-3-Vision architecture\n\nCephalo is a series of multimodal materials science focused vision large language models (V-LLMs) designed to integrate visual and linguistic data for advanced understanding and interaction in human-AI or multi-agent AI frameworks. \n\n![image/png](https://cdn-uploads.huggingface.co/production/uploads/623ce1c6b66fedf374859fe7/kl5GWBP9WS0D4uwd1t3S7.png)\n\nThis repository explains how to create a Mixture-of-Expert model based on one or several Phi-3-Vision-128K models. The model architecture is as follows:\n\n![image/png](https://cdn-uploads.huggingface.co/production/uploads/623ce1c6b66fedf374859fe7/b7BK8ZtDzTMsyFDi0wP3w.png)\n\nModel weights and examples are provided at: [https://huggingface.co/lamm-mit/Cephalo-Phi-3-MoE-vision-128k-3x4b-beta](https://huggingface.co/lamm-mit/Cephalo-Phi-3-MoE-vision-128k-3x4b-beta)\n\n## Download MoE Model and Sample inference code\n\n```markdown\npip install transformers -U\n```\n\n```python\nimport torch\nfrom transformers import AutoModelForCausalLM, AutoProcessor,AutoConfig  \n\ndef count_parameters(model):\n    total_params = sum(p.numel() for p in model.parameters())\n    trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n    #number of parameters in b\n    return total_params/1e9, trainable_params/1e9\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nmodel_name_moe = \"lamm-mit/Cephalo-Phi-3-MoE-vision-128k-3x4b-beta\"\n\nprocessor = AutoProcessor.from_pretrained(model_name_moe, trust_remote_code=True) \nmoe_model = AutoModelForCausalLM.from_pretrained(\n    model_name_moe,\n    trust_remote_code=True,  torch_dtype=torch.bfloat16,    \n).to(device)\ncount_parameters(moe_model)\n```\n\n## Make a Phi-3-V-MoE model from scratch using several pre-trained models\n\nYou can either download .py files from this repository (see folder [Phi_3V_MoE/](https://github.com/lamm-mit/Cephalo-Phi-3-MoE/tree/main/Phi_3V_MoE) or download them directly from our Hugging Face repository. \n\nThese codes implement the Phi-3-V and the Mixture-of-Expert Vision model from scratch. \n\n```markdown\npip install huggingface_hub\n```\n\n```python\nfrom huggingface_hub import HfApi, hf_hub_download\nfrom tqdm.notebook import tqdm\nimport os\nimport shutil\n\n# Repository details\nrepo_id = \"lamm-mit/Cephalo-Phi-3-MoE-vision-128k-3x4b-beta\"\napi = HfApi()\n\n# List all files in the repository\nfiles_in_repo = api.list_repo_files(repo_id)\n\n# Filter for .py files\npy_files = [file for file in files_in_repo if file.endswith('.py')]\n\n# Directory to save the downloaded files\nsave_dir = \"./Phi_3V_MoE/\"\nos.makedirs(save_dir, exist_ok=True)\n\n# Download each .py file\nfor file_name in tqdm(py_files):\n    file_path = hf_hub_download(repo_id=repo_id, filename=file_name)\n    new_path = os.path.join(save_dir, file_name)\n    shutil.move(file_path, new_path)\n    print(f\"Downloaded: {file_name}\")\n\nprint(\"Download completed.\")\n```\n\nDownload models that will form the experts, as well as the base model \n\n```python\nfrom Phi_3V_MoE.moe_phi3_v import Phi3VForCausalLMMoE, Phi3VForCausalLMMoEConfig\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n#Model specialized in bio-inspired/mechanics and materials\nmodel_name_1 = f\"lamm-mit/Cephalo-Phi-3-vision-128k-4b-beta\"\nmodel_1 = AutoModelForCausalLM.from_pretrained(\n    model_name_1,\n    trust_remote_code=True,  torch_dtype=torch.bfloat16, \n    \n).to(device)\n\n#Original model\nmodel_name_2 = f\"microsoft/Phi-3-vision-128k-instruct\"\nmodel_2 = AutoModelForCausalLM.from_pretrained(\n    model_name_2,\n    trust_remote_code=True,  torch_dtype=torch.bfloat16, \n    \n).to(device)\n\n#Model trained on conversion of images to LaTeX formulas\nmodel_name_3 = f\"lamm-mit/Cephalo-LaTeX-Phi-3-vision-128k-4b-alpha\"\nmodel_3 = AutoModelForCausalLM.from_pretrained(\n    model_name_3,\n    trust_remote_code=True,  torch_dtype=torch.bfloat16, \n    \n).to(device)\n\ndtype = torch.bfloat16  # Desired dtype for new layers in MoE model\n\n# Initialize the models\nbase_model = copy.deepcopy(model_2)  # Your base model\nexpert_models = [model_1, model_2,  model_3  ]  # List of expert models\n \n# Load a processor (e.g. from base model)\nprocessor = AutoProcessor.from_pretrained(model_name_2, trust_remote_code=True) \n\n# Create the config\nconfig =  AutoConfig.from_pretrained(model_name_2, trust_remote_code=True)\n\n# Create the MoE model\nmoe_config = Phi3VForCausalLMMoEConfig(config=config, k=1, num_expert_models=len (expert_models))\nmoe_model = Phi3VForCausalLMMoE(moe_config, base_model, expert_models,  layer_dtype = dtype).to(device)\n\ncount_parameters(expert_models[0]),count_parameters(moe_model)\n```\n\n### Training the gating networks\n\nTo train the gating networks, you need to provide sample prompts for each of the experts. Sample prompts consist of text and image data. You must match the number of experts you have, designed by k above. \n\nTo get text data, you can use the processor/chat template:\n\n```python\nmessages = [ {\"role\": \"user\", \"content\": \"\u003c|image_1|\u003e\\nWhat is shown in this image, and what is the relevance for materials design?\"}, ]\nprompt = processor.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)\nprompt\n```\n\nIn the following example we show how training of the gating layers is done. The training set consists of images and prompt. The first item in the list are the prompts for expert 1, the second item the prompts for expert 2, and so on. \n\nSample training set and process to train (for simplicity we use only three images, one characteristic of each expert):\n```python\nfrom PIL import Image\nimport requests\n\nimage_1 = Image.open(requests.get(\"https://d2r55xnwy6nx47.cloudfront.net/uploads/2018/02/Ants_Lede1300.jpg\", stream=True).raw) \nimage_2 = Image.open(requests.get(\"https://https://images.pexels.com/photos/106399/pexels-photo-106399.jpeg\", stream=True).raw) \nimage_3 = Image.open(requests.get(\"https://upload.wikimedia.org/wikipedia/commons/a/a0/Euplectella_aspergillum_Okeanos.jpg\", stream=True).raw) \n\nprompts_per_expert = [\n    [{\"text\": \"\u003c|user|\u003e\\n\u003c|image_1|\u003e\\nPrompt 1 for expert 1\u003c|end|\u003e\\n\u003c|assistant|\u003e\\n\", \"image\": [image_1]}, \n     {\"text\": \"\u003c|user|\u003e\\n\u003c|image_1|\u003e\\nPrompt 2 for expert 1\u003c|end|\u003e\\n\u003c|assistant|\u003e\\n\", \"image\": [image_1]}],\n\n    [{\"text\": \"\u003c|user|\u003e\\n\u003c|image_1|\u003e\\nPrompt 1 for expert 2\u003c|end|\u003e\\n\u003c|assistant|\u003e\\n\", \"image\": [image_2]}, \n     {\"text\": \"\u003c|user|\u003e\\n\u003c|image_1|\u003e\\nPrompt 2 for expert 2\u003c|end|\u003e\\n\u003c|assistant|\u003e\\n\", \"image\": [image_2]}],\n\n    [{\"text\": \"\u003c|user|\u003e\\n\u003c|image_1|\u003e\\nPrompt 1 for expert 3\u003c|end|\u003e\\n\u003c|assistant|\u003e\\n\", \"image\": [image_3]}, \n     {\"text\": \"\u003c|user|\u003e\\n\u003c|image_1|\u003e\\nPrompt 2 for expert 3\u003c|end|\u003e\\n\u003c|assistant|\u003e\\n\", \"image\": [image_3]}],\n]\n\n# Train gating layers using the provided prompts\ngating_layer_params = moe_model.train_gating_layer_params_from_hidden_states(processor, prompts_per_expert,\n                                              epochs=1000,\n                                              loss_steps=100,\n                                              lr=5e-5,\n                                          )\n\n# Set parameters\nmoe_model.set_gating_layer_params(gating_layer_params)\n```\n\n![image/png](https://cdn-uploads.huggingface.co/production/uploads/623ce1c6b66fedf374859fe7/xzZwBIw1yYr9v7xYblCNZ.png)\n\n### Peparing gating network for full training\n\nTo freeze all parameters in the model except for the gating neural networks, you can use:\n\n```python\nfreeze_except_gating_layers(moe_model)\ncount_parameters(moe_model)\n```\nYou can unfreeze:\n```python\nun_freeze_all(moe_model)\n```\n\nDefine FT_repo_id to push on HF hub/save model:\n```\nFT_repo_id='xxxxx/' #\u003crepo_ID\u003e\n```\n\n```\nfrom datasets import load_dataset\n\ntrain_dataset = load_dataset(\"lamm-mit/Cephalo-Wikipedia-Materials\", split=\"train\")\n```\n\n```python\nimport random\n\nclass MyDataCollator:\n    def __init__(self, processor):\n        self.processor = processor\n\n    def __call__(self, examples):\n        texts = []\n        images = []\n        for example in examples:\n            image = example[\"image\"]\n            question = example[\"query\"] \n            answer = example[\"answer\"]            \n            messages = [ {\n                            \"role\": \"user\",  \"content\": '\u003c|image_1|\u003e\\n'+question},\n                           {\"role\": \"assistant\", \"content\": f\"{answer}\"}, ]\n                \n            text = processor.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)\n                \n            images.append(image)\n             \n        batch = processor(text=text, images=[image], return_tensors=\"pt\", padding=True\n            \n        labels = batch[\"input_ids\"].clone() \n        labels[labels \u003c0] = -100 \n\n        batch[\"labels\"] = labels\n\n        return batch\n\ndata_collator = MyDataCollator(processor)\n```\nThen set up trainer, and train:\n```python\nfrom transformers import TrainingArguments, Trainer\n\noptim = \"paged_adamw_8bit\"\n\ntraining_args = TrainingArguments(\n    num_train_epochs=2,\n    per_device_train_batch_size=1,\n    gradient_accumulation_steps=4,\n    warmup_steps=250,\n    learning_rate=1e-5,\n    weight_decay=0.01,\n    logging_steps=25,\n    output_dir=\"output_training\",\n    optim=optim,\n    save_strategy=\"steps\",\n    save_steps=1000,\n    save_total_limit=16,\n    #fp16=True,\n    bf16=True,  \n    push_to_hub_model_id=FT_repo_id,\n    remove_unused_columns=False,\n    report_to=\"none\",\n)\n\ntrainer = Trainer(\n    model=moe_model,\n    args=training_args,\n    data_collator=data_collator,\n    train_dataset=train_dataset,\n)\n\ntrainer.train()\n```\n\n## More details on inference \n\n### Chat Format\n\nGiven the nature of the training data, the Cephalo-Phi-3-vision-128k-4b-beta model is best suited for a single image input wih prompts using the chat format as follows. \nYou can provide the prompt as a single image with a generic template as follow:\n```raw\n\u003c|user|\u003e\\n\u003c|image_1|\u003e\\n{prompt}\u003c|end|\u003e\\n\u003c|assistant|\u003e\\n \n```\n\nwhere the model generates the text after `\u003c|assistant|\u003e` . For multi-turn conversations, the prompt should be formatted as follows:\n\n```raw\n\u003c|user|\u003e\\n\u003c|image_1|\u003e\\n{prompt_1}\u003c|end|\u003e\\n\u003c|assistant|\u003e\\n{response_1}\u003c|end|\u003e\\n\u003c|user|\u003e\\n{prompt_2}\u003c|end|\u003e\\n\u003c|assistant|\u003e\\n \n```\n\n## Sample inference code\n\nThis code snippets show how to get quickly started on a GPU:\n\n```python\nfrom PIL import Image \nimport requests\nfrom transformers import AutoModelForCausalLM, AutoProcessor,AutoConfig  \n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nmodel_name_moe = \"lamm-mit/Cephalo-Phi-3-MoE-vision-128k-3x4b-beta\"\n\nprocessor = AutoProcessor.from_pretrained(model_name_moe, trust_remote_code=True) \nmoe_model = AutoModelForCausalLM.from_pretrained(\n    model_name_moe,\n    trust_remote_code=True,  torch_dtype=torch.bfloat16,    \n).to(device)\n\nquestion = \"What is shown in this image, and what is the relevance for materials design? Include a discussion of multi-agent AI.\"\n\nmessages = [ \n    {\"role\": \"user\", \"content\": f\"\u003c|image_1|\u003e\\n{question}\"}, \n    ] \n\nurl = \"https://d2r55xnwy6nx47.cloudfront.net/uploads/2018/02/Ants_Lede1300.jpg\" \n\nimage = Image.open(requests.get(url, stream=True).raw) \n\nprompt = processor.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)\n\ninputs = processor(prompt, [image], return_tensors=\"pt\").to(\"cuda:0\") \n\ngeneration_args = { \n                    \"max_new_tokens\": 256, \n                    \"temperature\": 0.1, \n                    \"do_sample\": True, \n                    \"stop_strings\": ['\u003c|end|\u003e',\n                                     '\u003c|endoftext|\u003e'],\n                    \"tokenizer\": processor.tokenizer,\n                  } \n\ngenerate_ids = moe_model.generate(**inputs, eos_token_id=processor.tokenizer.eos_token_id, **generation_args) \n\n# remove input tokens \ngenerate_ids = generate_ids[:, inputs['input_ids'].shape[1]:]\nresponse = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] \n\nprint(response) \n```\nSample output:\n\n![image/png](https://cdn-uploads.huggingface.co/production/uploads/623ce1c6b66fedf374859fe7/5n6oRNHrfwHkBX0QertZp.png)\n\u003csmall\u003eImage by [Vaishakh Manohar](https://www.quantamagazine.org/the-simple-algorithm-that-ants-use-to-build-bridges-20180226/)\u003c/small\u003e\n\n\u003cpre style=\"white-space: pre-wrap;\"\u003e\nThe image shows a group of red ants (Solenopsis invicta) climbing over a vertical wooden post. The ants are using their long legs and antennae to navigate the rough surface of the wood, demonstrating their ability to adapt to different materials and environments. This behavior is relevant for materials design because it highlights the importance of considering the interactions between materials and living organisms, such as ants, when designing new materials.\n\nMulti-agent AI (Artificial Intelligence) is a field of study that focuses on the development of AI systems that can work together with other AI systems to achieve a common goal. In the context of this image, multi-agent AI could be used to design materials that are more compatible with the natural behaviors of living organisms, such as ants, and that can adapt to different environments and conditions.\n\nBy studying the behavior of ants and other living organisms, researchers can gain insights into how materials can be designed to better interact with these organisms and to better mimic their natural behaviors. This can lead to the development of new materials that are more sustainable, efficient, and effective in a variety of applications.\n\nIn summary, the image of red ants climbing over a wooden post highlights the importance of considering the interactions between materials and living organisms when designing new materials, and the potential of multi-agent AI to help achieve this goal.\n\u003c/pre\u003e\n\n## Citation\n\nPlease cite as:\n\n```bibtex\n@article{Buehler_Cephalo_2024,\n  title={Cephalo: Multi-Modal Vision-Language Models for Bio-Inspired Materials Analysis and Design},\n  author={Markus J. Buehler},\n  journal={arXiv preprint arXiv:2405.19076},\n  year={2024}\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flamm-mit%2Fcephalo-phi-3-vision-moe","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flamm-mit%2Fcephalo-phi-3-vision-moe","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flamm-mit%2Fcephalo-phi-3-vision-moe/lists"}