{"id":17596225,"url":"https://github.com/lamm-mit/cephalo","last_synced_at":"2025-06-19T08:32:12.646Z","repository":{"id":241772383,"uuid":"807069285","full_name":"lamm-mit/Cephalo","owner":"lamm-mit","description":null,"archived":false,"fork":false,"pushed_at":"2024-07-23T09:27:58.000Z","size":11545,"stargazers_count":10,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-30T12:41:38.476Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Jupyter Notebook","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","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":"LICENSE","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-28T12:29:13.000Z","updated_at":"2025-01-09T15:32:29.000Z","dependencies_parsed_at":"2024-07-14T10:46:53.050Z","dependency_job_id":"0fc8d4e4-3346-4aab-b7df-668cf7a8486c","html_url":"https://github.com/lamm-mit/Cephalo","commit_stats":null,"previous_names":["lamm-mit/cephalo"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lamm-mit%2FCephalo","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lamm-mit%2FCephalo/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lamm-mit%2FCephalo/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lamm-mit%2FCephalo/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lamm-mit","download_url":"https://codeload.github.com/lamm-mit/Cephalo/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251644827,"owners_count":21620630,"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:27.816Z","updated_at":"2025-04-30T04:50:56.569Z","avatar_url":"https://github.com/lamm-mit.png","language":"Jupyter Notebook","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Cephalo: Multi-Modal Vision-Language Models for Bio-Inspired Materials Analysis and Design\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\nA novel aspect of Cephalo's development is the innovative dataset generation method. The extraction process employs advanced algorithms to accurately detect and separate images and their corresponding textual descriptions from complex PDF documents. It involves extracting images and captions from PDFs to create well-reasoned image-text pairs, utilizing large language models (LLMs) for natural language processing. These image-text pairs are then refined and validated through LLM-based NLP processing, ensuring high-quality and contextually relevant data for training. \n\nCephalo can interpret complex visual scenes and generating contextually accurate language descriptions and answer queries. \n\nThe models are developed to process diverse inputs, including images and text, facilitating a broad range of applications such as image captioning, visual question answering, and multimodal content generation. The architecture combines a vision encoder model and an autoregressive transformer to process complex natural language understanding. \n\n![image/png](https://cdn-uploads.huggingface.co/production/uploads/623ce1c6b66fedf374859fe7/kl5GWBP9WS0D4uwd1t3S7.png)\n\nCephalo provides a robust framework for multimodal interaction and understanding, including the development of complex generative pipelines to create 2D and 3D renderings of material microstructures as input for additive manufacturing methods.\n\n## Information about this repository\n\nModels are provided at [https://huggingface.co/lamm-mit/cephalo/](https://huggingface.co/lamm-mit/cephalo/). This repository provides additional codes, tools and analysis associated with the models. \n\n## Getting Started: Inference\n\n[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/lamm-mit/Cephalo/blob/main/Cephalo%20Inference%20Colab.ipynb)\n\nOpen the Colab notebook above, or follow the instructions at [https://huggingface.co/lamm-mit/cephalo](https://huggingface.co/lamm-mit/cephalo) to get the model running on your local machine.\n\nA simple example:\n\n\n```python\nfrom PIL import Image \nimport requests \nfrom transformers import AutoModelForCausalLM \nfrom transformers import AutoProcessor \n\nmodel_id = \"lamm-mit/Cephalo-Phi-3-vision-128k-4b-beta\" \n\nmodel = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", trust_remote_code=True, torch_dtype=\"auto\")\n\nprocessor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True) \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\": 512, \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 = 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```\n## Model merging and Training Script\n\n- Model merging and training script: [Cephalo Model Merging 10b.ipynb](https://github.com/lamm-mit/Cephalo/blob/main/Cephalo%20Model%20Merging%20-%2010b.ipynb)\n\n## Overview of Models\n\n###  4b models\n\n- [Cephalo-Phi-3-vision-128k-4b-alpha](https://huggingface.co/lamm-mit/Cephalo-Phi-3-vision-128k-4b-alpha)\n  - Base version of the Cephalo-Phi-3 model, trained on GPT-4o distilled image-text data from Wikipedia and scientific papers. Good baseline model, but struggles in longer conversations. Context length of 128,000 tokens. \n- [Cephalo-Phi-3-vision-128k-4b-beta](https://huggingface.co/lamm-mit/Cephalo-Phi-3-vision-128k-4b-beta)\n  - Improved version of the Cephalo-Phi-3 model, trained on GPT-4o and Idefics-2 distilled image-text data from Wikipedia and scientific papers, as well as a large text-only corpus. Provides nuanced responses, with excellent reasoning. Context length of 128,000 tokens. \n\n### 8b models\n\n- [Cephalo-Idefics-2-vision-8b-alpha](https://huggingface.co/lamm-mit/Cephalo-Idefics-2-vision-8b-alpha)\n  - Trained on Idefics-2 distilled image-text data from Wikipedia and scientific papers. Gives shorter answers, to the point, and generaly accurate.\n- [Cephalo-Idefics-2-vision-8b-beta](https://huggingface.co/lamm-mit/Cephalo-Idefics-2-vision-8b-beta)\n  - Trained on GPT-4o distilled image-text data from Wikipedia and scientific papers. Gives longer answers, with enhanced reasoning. Can struggle with complex concepts.  \n- [Cephalo-Llava-v1.6-Mistral-8b-alpha](https://huggingface.co/lamm-mit/Cephalo-Llava-v1.6-Mistral-8b-alpha)\n  - Trained on GPT-4o distilled image-text data from Wikipedia, with low-resolution images. Does not perform well on multiple image queries, and has some inconsistencies in understanding.  \n\n### Merged 10b models\n\n- [Cephalo-Idefics-2-vision-10b-alpha](https://huggingface.co/lamm-mit/Cephalo-Idefics-2-vision-10b-alpha)\n  - Merged model, 32+8=40 layers, checkpoint after first epoch. Trained on GPT-4o distilled image-text data from Wikipedia and scientific papers.\n- [Cephalo-Idefics-2-vision-10b-beta](https://huggingface.co/lamm-mit/Cephalo-Idefics-2-vision-10b-beta)\n  - Merged model, 32+8=40 layers, checkpoint after second epoch. Trained on GPT-4o distilled image-text data from Wikipedia and scientific papers.\n\n### Merged 12b models\n\n- [lamm-mit/Cephalo-Idefics-2-vision-12b-alpha](https://huggingface.co/lamm-mit/Cephalo-Idefics-2-vision-12b-alpha)\n  - Merged model, 32+16=48 layers, checkpoint after first epoch. Trained on GPT-4o distilled image-text data from Wikipedia and scientific papers (dataset derivived from both Idefics-2 and GPT-4o distillation of the paper corpus).\n\n![image/png](https://cdn-uploads.huggingface.co/production/uploads/623ce1c6b66fedf374859fe7/3Nfhn3f3FyK7Zgdg9GKJQ.png)\n\nThe image shows a summary of model merging approach, constructing larger models from smaller pre-trained building blocks. a, Fine-tuning the base model. b, Constructing the larger, merged model by combining the whole or parts of smaller models. c, Fine-tuning the integrated hybrid, merged, model.  \n\n### Mixture-of-Experts models (including training and cookbook)\n\nCodes and training examples are provided for both the Phi-3-Vision and Idefics2 based Cephalo models (with base model size of 4b and 8b parameters, respectively). \n\n- [lamm-mit/Cephalo-Phi-3-MoE-vision-128k-3x4b-beta](https://huggingface.co/lamm-mit/Cephalo-Phi-3-MoE-vision-128k-3x4b-beta)\n  - Mixture-of-expert model based on several smaller Cephalo-Phi-3 models.\n- [lamm-mit/Cephalo-Idefics2-MoE]([https://github.com/lamm-mit/Cephalo-Idefics2-MoE](https://huggingface.co/lamm-mit/Cephalo-Idefics2-vision-3x8b-beta))\n  - Mixture-of-expert model based on several smaller Cephalo-Idefics2 models.\n\nAn easy to follow, annotated cookbook on how to create a MoE model from scratch is provided at: [https://huggingface.co/blog/mjbuehler/phi-3-vision-cephalo-moe](https://huggingface.co/blog/mjbuehler/phi-3-vision-cephalo-moe).\n\n![image/png](https://cdn-uploads.huggingface.co/production/uploads/623ce1c6b66fedf374859fe7/NK9KNOxmnVtn_PzwJtKPR.png)\n\n### Training script \n\nA training script is provided here: [Cephalo_Fine-Tune.ipynb](https://github.com/lamm-mit/Cephalo/blob/main/Cephalo_Fine-Tune.ipynb). \n\n![image](https://github.com/user-attachments/assets/7338974e-b374-4ace-8e28-cfb594a309be)\n\n### Fast inference with mistral.rs\n\nStart an OpenAI comptabile server in a terminal:\n```\n./mistralrs_server --port 1234 vision-plain -m lamm-mit/Cephalo-Phi-3-vision-128k-4b-beta -a phi3v\n```\nThen, you can use it as follows:\n```\nimport openai\nimport httpx\nimport textwrap, json\n\ndef log_response(response: httpx.Response):\n    request = response.request\n    print(f\"Request: {request.method} {request.url}\")\n    print(\"  Headers:\")\n    for key, value in request.headers.items():\n        if key.lower() == \"authorization\":\n            value = \"[...]\"\n        if key.lower() == \"cookie\":\n            value = value.split(\"=\")[0] + \"=...\"\n        print(f\"    {key}: {value}\")\n    print(\"  Body:\")\n    try:\n        request_body = json.loads(request.content)\n        print(textwrap.indent(json.dumps(request_body, indent=2), \"    \"))\n    except json.JSONDecodeError:\n        print(textwrap.indent(request.content.decode(), \"    \"))\n    print(f\"Response: status_code={response.status_code}\")\n    print(\"  Headers:\")\n    for key, value in response.headers.items():\n        if key.lower() == \"set-cookie\":\n            value = value.split(\"=\")[0] + \"=...\"\n        print(f\"    {key}: {value}\")\n\n\nopenai.api_key = \"EMPTY\"\nopenai.base_url = \"http://localhost:1234/v1/\"\n\n# Enable this to log requests and responses\n# openai.http_client = httpx.Client(\n#     event_hooks={\"request\": [print], \"response\": [log_response]}\n# )\n\ncompletion = openai.chat.completions.create(\n    model=\"phi3v\",\n    messages=[\n        {\n            \"role\": \"user\",\n            \"content\": [\n                {\n                    \"type\": \"image_url\",\n                    \"image_url\": {\n                        \"url\": \"https://d2r55xnwy6nx47.cloudfront.net/uploads/2018/02/Ants_Lede1300.jpg\"\n                    },\n                },\n                {\n                    \"type\": \"text\",\n                    \"text\": \"\u003c|image_1|\u003e\\nWhat is shown in this image, and what is the relevance for materials design? Include a discussion of multi-agent AI.\",\n                },\n            ],\n        },\n    ],\n    max_tokens=256,\n    frequency_penalty=1.0,\n    top_p=0.1,\n    temperature=0.3,\n)\nresp = completion.choices[0].message.content\nprint(resp)\n```\nMore details on mistral.rs (including more sample scripts), see: https://github.com/EricLBuehler/mistral.rs\n\n### Additional codes and tools\n\nAdditional codes and tools are provided at [https://github.com/lamm-mit/Cephalo](https://github.com/lamm-mit/Cephalo).\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  = {M.J. Buehler},\n    journal = {arXiv},\n    year    = {2024},\n    volume  = {},\n    pages   = {},\n    url     = {https://arxiv.org/abs/2405.19076}\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flamm-mit%2Fcephalo","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flamm-mit%2Fcephalo","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flamm-mit%2Fcephalo/lists"}