Views
No views yet


pip install transformers -U1import torch
2from transformers import AutoModelForCausalLM, AutoProcessor,AutoConfig
3
4def count_parameters(model):
5 total_params = sum(p.numel() for p in model.parameters())
6 trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
7 #number of parameters in b
8 return total_params/1e9, trainable_params/1e9
9
10device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
11
12model_name_moe = "lamm-mit/Cephalo-Phi-3-MoE-vision-128k-3x4b-beta"
13
14processor = AutoProcessor.from_pretrained(model_name_moe, trust_remote_code=True)
15moe_model = AutoModelForCausalLM.from_pretrained(
16 model_name_moe,
17 trust_remote_code=True, torch_dtype=torch.bfloat16,
18).to(device)
19count_parameters(moe_model)pip install huggingface_hub1from huggingface_hub import HfApi, hf_hub_download
2from tqdm.notebook import tqdm
3import os
4import shutil
5
6# Repository details
7repo_id = "lamm-mit/Cephalo-Phi-3-MoE-vision-128k-3x4b-beta"
8api = HfApi()
9
10# List all files in the repository
11files_in_repo = api.list_repo_files(repo_id)
12
13# Filter for .py files
14py_files = [file for file in files_in_repo if file.endswith('.py')]
15
16# Directory to save the downloaded files
17save_dir = "./Phi_3V_MoE/"
18os.makedirs(save_dir, exist_ok=True)
19
20# Download each .py file
21for file_name in tqdm(py_files):
22 file_path = hf_hub_download(repo_id=repo_id, filename=file_name)
23 new_path = os.path.join(save_dir, file_name)
24 shutil.move(file_path, new_path)
25 print(f"Downloaded: {file_name}")
26
27print("Download completed.")1from Phi_3V_MoE.moe_phi3_v import Phi3VForCausalLMMoE, Phi3VForCausalLMMoEConfig
2
3device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
4
5#Model specialized in bio-inspired/mechanics and materials
6model_name_1 = f"lamm-mit/Cephalo-Phi-3-vision-128k-4b-beta"
7model_1 = AutoModelForCausalLM.from_pretrained(
8 model_name_1,
9 trust_remote_code=True, torch_dtype=torch.bfloat16,
10
11).to(device)
12
13#Original model
14model_name_2 = f"microsoft/Phi-3-vision-128k-instruct"
15model_2 = AutoModelForCausalLM.from_pretrained(
16 model_name_2,
17 trust_remote_code=True, torch_dtype=torch.bfloat16,
18
19).to(device)
20
21#Model trained on conversion of images to LaTeX formulas
22model_name_3 = f"lamm-mit/Cephalo-LaTeX-Phi-3-vision-128k-4b-beta"
23model_3 = AutoModelForCausalLM.from_pretrained(
24 model_name_3,
25 trust_remote_code=True, torch_dtype=torch.bfloat16,
26
27).to(device)
28
29dtype = torch.bfloat16 # Desired dtype for new layers in MoE model
30
31# Initialize the models
32base_model = copy.deepcopy(model_2) # Your base model
33expert_models = [model_1, model_2, model_3 ] # List of expert models
34
35# Load a processor (e.g. from base model)
36processor = AutoProcessor.from_pretrained(model_name_2, trust_remote_code=True)
37
38# Create the config
39config = AutoConfig.from_pretrained(model_name_2, trust_remote_code=True)
40
41# Create the MoE model
42moe_config = Phi3VForCausalLMMoEConfig(config=config, k=1, num_expert_models=len (expert_models))
43moe_model = Phi3VForCausalLMMoE(moe_config, base_model, expert_models, layer_dtype = dtype).to(device)
44
45count_parameters(expert_models[0]),count_parameters(moe_model)1messages = [ {"role": "user", "content": "<|image_1|>\nWhat is shown in this image, and what is the relevance for materials design?"}, ]
2prompt = processor.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
3prompt1from PIL import Image
2import requests
3
4image_1 = Image.open(requests.get("https://d2r55xnwy6nx47.cloudfront.net/uploads/2018/02/Ants_Lede1300.jpg", stream=True).raw)
5image_2 = Image.open(requests.get("https://https://images.pexels.com/photos/106399/pexels-photo-106399.jpeg", stream=True).raw)
6image_3 = Image.open(requests.get("https://upload.wikimedia.org/wikipedia/commons/a/a0/Euplectella_aspergillum_Okeanos.jpg", stream=True).raw)
7
8prompts_per_expert = [
9 [{"text": "<|user|>\n<|image_1|>\nPrompt 1 for expert 1<|end|>\n<|assistant|>\n", "image": [image_1]},
10 {"text": "<|user|>\n<|image_1|>\nPrompt 2 for expert 1<|end|>\n<|assistant|>\n", "image": [image_1]}],
11
12 [{"text": "<|user|>\n<|image_1|>\nPrompt 1 for expert 2<|end|>\n<|assistant|>\n", "image": [image_2]},
13 {"text": "<|user|>\n<|image_1|>\nPrompt 2 for expert 2<|end|>\n<|assistant|>\n", "image": [image_2]}],
14
15 [{"text": "<|user|>\n<|image_1|>\nPrompt 1 for expert 3<|end|>\n<|assistant|>\n", "image": [image_3]},
16 {"text": "<|user|>\n<|image_1|>\nPrompt 2 for expert 3<|end|>\n<|assistant|>\n", "image": [image_3]}],
17]
18
19# Train gating layers using the provided prompts
20gating_layer_params = moe_model.train_gating_layer_params_from_hidden_states(processor, prompts_per_expert,
21 epochs=1000,
22 loss_steps=100,
23 lr=5e-5,
24 )
25
26# Set parameters
27moe_model.set_gating_layer_params(gating_layer_params)
1freeze_except_gating_layers(moe_model)
2count_parameters(moe_model)un_freeze_all(moe_model)FT_repo_id='xxxxx/' #<repo_ID>from datasets import load_dataset
train_dataset = load_dataset("lamm-mit/Cephalo-Wikipedia-Materials", split="train")1import random
2
3class MyDataCollator:
4 def __init__(self, processor):
5 self.processor = processor
6
7 def __call__(self, examples):
8 texts = []
9 images = []
10 for example in examples:
11 image = example["image"]
12 question = example["query"]
13 answer = example["answer"]
14 messages = [ {
15 "role": "user", "content": '<|image_1|>\n'+question},
16 {"role": "assistant", "content": f"{answer}"}, ]
17
18 text = processor.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)
19
20 images.append(image)
21
22 batch = processor(text=text, images=[image], return_tensors="pt", padding=True
23
24 labels = batch["input_ids"].clone()
25 labels[labels <0] = -100
26
27 batch["labels"] = labels
28
29 return batch
30
31data_collator = MyDataCollator(processor)1from transformers import TrainingArguments, Trainer
2
3optim = "paged_adamw_8bit"
4
5training_args = TrainingArguments(
6 num_train_epochs=2,
7 per_device_train_batch_size=1,
8 gradient_accumulation_steps=4,
9 warmup_steps=250,
10 learning_rate=1e-5,
11 weight_decay=0.01,
12 logging_steps=25,
13 output_dir="output_training",
14 optim=optim,
15 save_strategy="steps",
16 save_steps=1000,
17 save_total_limit=16,
18 #fp16=True,
19 bf16=True,
20 push_to_hub_model_id=FT_repo_id,
21 remove_unused_columns=False,
22 report_to="none",
23)
24
25trainer = Trainer(
26 model=moe_model,
27 args=training_args,
28 data_collator=data_collator,
29 train_dataset=train_dataset,
30)
31
32trainer.train()<|user|>\n<|image_1|>\n{prompt}<|end|>\n<|assistant|>\n <|assistant|> . For multi-turn conversations, the prompt should be formatted as follows:<|user|>\n<|image_1|>\n{prompt_1}<|end|>\n<|assistant|>\n{response_1}<|end|>\n<|user|>\n{prompt_2}<|end|>\n<|assistant|>\n 1from PIL import Image
2import requests
3from transformers import AutoModelForCausalLM, AutoProcessor,AutoConfig
4
5device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
6
7model_name_moe = "lamm-mit/Cephalo-Phi-3-MoE-vision-128k-3x4b-beta"
8
9processor = AutoProcessor.from_pretrained(model_name_moe, trust_remote_code=True)
10moe_model = AutoModelForCausalLM.from_pretrained(
11 model_name_moe,
12 trust_remote_code=True, torch_dtype=torch.bfloat16,
13).to(device)
14
15question = "What is shown in this image, and what is the relevance for materials design? Include a discussion of multi-agent AI."
16
17messages = [
18 {"role": "user", "content": f"<|image_1|>\n{question}"},
19 ]
20
21url = "https://d2r55xnwy6nx47.cloudfront.net/uploads/2018/02/Ants_Lede1300.jpg"
22
23image = Image.open(requests.get(url, stream=True).raw)
24
25prompt = processor.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
26
27inputs = processor(prompt, [image], return_tensors="pt").to("cuda:0")
28
29generation_args = {
30 "max_new_tokens": 256,
31 "temperature": 0.1,
32 "do_sample": True,
33 "stop_strings": ['<|end|>',
34 '<|endoftext|>'],
35 "tokenizer": processor.tokenizer,
36 }
37
38generate_ids = moe_model.generate(**inputs, eos_token_id=processor.tokenizer.eos_token_id, **generation_args)
39
40# remove input tokens
41generate_ids = generate_ids[:, inputs['input_ids'].shape[1]:]
42response = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
43
44print(response) 

1@article{Buehler_Cephalo_2024,
2 title={Cephalo: Multi-Modal Vision-Language Models for Bio-Inspired Materials Analysis and Design},
3 author={Markus J. Buehler},
4 journal={arXiv preprint arXiv:2405.19076},
5 year={2024}
6}