Views
No views yet


1import torch
2from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
3
4def generate_response(model, tokenizer, text_input="Biology offers amazing materials. Tell me more!", system_prompt='You are a materials scientist.',
5 num_return_sequences=1, temperature=0.3, max_new_tokens=256, do_sample=True,
6 num_beams=1, eos_token_id=[2],
7 device='cuda', top_k=50, top_p=0.9, repetition_penalty=1.1, messages=None, ):
8
9 if messages is None:
10 if system_prompt:
11 messages = [{"role": "user", "content": system_prompt + text_input}]
12 else:
13 messages = [{"role": "user", "content": text_input}]
14 else:
15 messages.append({"role": "user", "content": text_input})
16
17 text_input = tokenizer.apply_chat_template(
18 messages,
19 tokenize=False,
20 add_generation_prompt=True
21 )
22
23 inputs = tokenizer([text_input], add_special_tokens=False, return_tensors='pt').to(device)
24
25 with torch.no_grad():
26 outputs = model.generate(
27 **inputs,
28 max_new_tokens=max_new_tokens,
29 temperature=temperature,
30 num_beams=num_beams,
31 top_k=top_k,
32 do_sample=do_sample,
33 top_p=top_p,
34 eos_token_id=eos_token_id,
35 num_return_sequences=num_return_sequences,
36 repetition_penalty=repetition_penalty,
37 )
38
39 outputs = outputs[:, inputs["input_ids"].shape[1]:]
40
41 return tokenizer.batch_decode(outputs.detach().cpu().numpy(), skip_special_tokens=True), messages
42
43def load_model(model_name, chat_template=None, compile_mode=None,
44 attn_implementation="flash_attention_2", quant=False):
45
46 if quant:
47 bnb_config4bit = BitsAndBytesConfig(
48 load_in_4bit=True,
49 bnb_4bit_quant_type="nf4",
50 bnb_4bit_compute_dtype=torch.bfloat16,
51 bnb_4bit_use_double_quant=True,
52 )
53 model = AutoModelForCausalLM.from_pretrained(
54 model_name,
55 trust_remote_code=True,
56 use_cache=False,
57 quantization_config=bnb_config4bit,
58 device_map="auto",
59 torch_dtype=torch.bfloat16,
60 attn_implementation=attn_implementation,
61 )
62 else:
63 model = AutoModelForCausalLM.from_pretrained(
64 model_name,
65 trust_remote_code=True,
66 use_cache=False,
67 device_map="auto",
68 torch_dtype=torch.bfloat16,
69 attn_implementation=attn_implementation,
70 )
71
72 if compile_mode:
73 model.generation_config.cache_implementation = "static"
74 model.forward = torch.compile(model.forward, mode=compile_mode, fullgraph=True)
75
76 tokenizer = AutoTokenizer.from_pretrained(
77 model_name,
78 trust_remote_code=True,
79 add_bos_token=False
80 )
81
82 if chat_template:
83 tokenizer.chat_template = chat_template
84
85 return model, tokenizer<|im_end|> as end token):1messages = [
2 {"role": "system", "content": "You are a biomaterials scientist."},
3 {"role": "user", "content": "What is the role of collagen in bone?"},
4 {"role": "assistant", "content": "Collagen is a key structural protein."},
5]
6prompt = tokenizer.apply_chat_template(
7 messages,
8 tokenize=False,
9 add_generation_prompt=True
10)
11print (prompt)1<|begin_of_text|><|im_start|>system
2You are a biomaterials scientist.<|im_end|>
3<|im_start|>user
4What is the role of collagen in bone?<|im_end|>
5<|im_start|>assistant
6Collagen is a key structural protein.<|im_end|>
7<|im_start|>assistantmodel, tokenizer,=load_model (model_name='lamm-mit/Bioinspired-SmolLM-1.7B-Instruct')1messages=[]
2result,messages=generate_response (model, tokenizer, text_input="Collagen and the Glass Bead Game, discuss their relationship.",
3 num_return_sequences=1, temperature=0.3,max_new_tokens=1024 , messages=[]
4 system_prompt="You are materials scientist. ",)
5
6for res in result:
7 print(res, "\n")
8
9messages.append ( {"role": "assistant", "content":result[0]}) 1result,messages=generate_response (model, tokenizer, text_input="Summarize the key points in JSON format.",num_return_sequences=1,
2 temperature=0.3,max_new_tokens=1024 , messages=messages)
3
4for res in result:
5 print(res, "\n")
6
7messages.append ( {"role": "assistant", "content":result[0]})
8
9<pre style="white-space: pre-wrap;">
10
11Here's a summary of collagen and the Glass Bead Game in JSON format:
12
13```json
14{
15 "collagen": {
16 "structure": "proteinous fibrous network",
17 "composition": "glycoprotein",
18 "properties": "high tensile strength, low stiffness",
19 "functions": "structural support, cell signaling, wound healing",
20 "types": ["alpha", "beta", "gamma", "delta"]
21 },
22 "glass bead game": {
23 "rules": "a strategy game where players collect and trade glass beads, simulating the process of collagen synthesis and mineralization",
24 "components": ["glass beads", "mineral deposits", "cell signaling molecules", "growth factors"],
25 "goal": "collect and trade the most beads to achieve mineralization and growth",
26 "rules of play": "players must collect beads, deposit them in cells, and stimulate mineralization through signaling molecules and growth factors",
27 "game mechanics": "players earn points for successful mineralization, trade beads for resources, and manage their cells' mineralization and growth rates"
28 },
29}
1@article{LuLuuBuehler2024,
2 title={Fine-tuning large language models for domain adaptation: Exploration of training strategies, scaling, model merging and synergistic capabilities},
3 author={Wei Lu and Rachel K. Luu and Markus J. Buehler},
4 journal={arXiv: https://arxiv.org/abs/2409.03444},
5 year={2024},
6}
7
8@article{LuuBuehler2023bioinspiredLLM,
9 title={BioinspiredLLM: Conversational Large Language Model for the Mechanics of Biological and Bio-Inspired Materials},
10 author={Rachel K. Luu and Markus J. Buehler},
11 year={2023},
12 journal={Advanced Science},
13 doi={10.1002/advs.202306724},
14 eprint={2309.08788},
15 archivePrefix={arXiv},
16 primaryClass={cs.LG},
17 url={https://arxiv.org/abs/2309.08788}
18}
19
20@article{Buehler2024XLoRA,
21 title={X-LoRA: Mixture of low-rank adapter experts, a flexible framework for large language models with applications in protein mechanics and molecular design},
22 author={Eric L. Buehler and Markus J. Buehler},
23 year={2024},
24 journal={APL Machine Learning},
25 volume={2},
26 number={2},
27 pages={026119},
28 doi={10.1063/5.0203126},
29 note={\url{https://doi.org/10.1063/5.0203126}}
30}