/ Модель

Характеристики

Контекст
2 048 токенов
Параметры
1,7 млрд
Лицензия
Apache 2.0
Архитектура
llama · dense
Базовая модель
SmolLM-1.7B
Библиотека
transformers
Опубликована
22 авг 2024

Bioinspired-SmolLM-1.7B-Instruct

Генерация текстаТекст → текст3 профессии

Компактная диалоговая модель для генерации текста и ответов на вопросы о биоинспирированных материалах и их механике.

45скачиваний за 30 дней5лайковвеса обновлены11 сен 2024

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Тесты пользователейпока нет

Никто ещё не опубликовал тест этой модели. Соберите бенчмарк из своих задач — результат появится здесь.

  1. Добавьте модель в бенчмарк

    Вместе с другими моделями категории «Текст» — сравнение идёт внутри одной категории.

  2. Опишите свои задачи

    Напишите запросы, при необходимости приложите файлы и эталонные ответы.

  3. Запустите и опубликуйте

    Модели ответят на каждую задачу, судья оценит ответы. Опубликованный результат появится на этой странице.

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

Bioinspired-SmolLM-1.7B-Instruct — компактная языковая модель команды LAMM-MIT, созданная на базе SmolLM-1.7B с продолженным предобучением, дообучением на инструкциях и оптимизацией предпочтений DPO. Она предназначена для диалогов и генерации текста по темам биоинспирированных материалов, биоматериалов и их механики; обучение включало около 5 000 научных статей в этой области и наборы инструкций и диалогов.

Модель использует плотную архитектуру LlamaForCausalLM, содержит 1,7 млрд параметров, принимает текст и имеет контекст до 2 048 токенов. Карточка демонстрирует диалоговый шаблон ChatML и примеры ответов на вопросы о материалах и биологии, однако пример также показывает, что ответы могут содержать вымышленные сведения. Поддержка русского языка не заявлена. Распространяется в формате Safetensors по лицензии Apache-2.0.

Сценарии применения

  • ответы на вопросы о биоматериалах и их механических свойствах
  • объяснение научных понятий из области биоинспирированных материалов
  • подготовка черновиков диалоговых ответов по научным статьям
  • извлечение и обобщение сведений о материалах в текстовом диалоге

Ограничения

Контекст ограничен 2 048 токенами; в примере README модель уверенно генерирует вымышленные сведения, поэтому ответы требуют проверки по научным источникам. Поддержка русского языка не заявлена.

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

lamm-mit/Bioinspired-SmolLM-1.7B-Instruct

This model was constructed from the SmolLM-1.7B base model using a combination of Continued Pre-training (CPT), Supervised fine-tuning (SFT), and DPO.

image/png The model was trained on a mix of publically available datasets and a corpus of around 5,000 scientific papers in the bio-inspired materials field. During the CPT phase, the raw text of all papers is used. During SFT and ORPO, the model is shown a high-quality mix of question-answer pairs and question-answer-rejected triples, respectively, along with other datasets to train the model for instructions and chat interactions.

image/png

Inference

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig

def generate_response(model, tokenizer, text_input="Biology offers amazing materials. Tell me more!", system_prompt='You are a materials scientist.',
                      num_return_sequences=1, temperature=0.3, max_new_tokens=256, do_sample=True,
                      num_beams=1, eos_token_id=[2],
                      device='cuda', top_k=50, top_p=0.9, repetition_penalty=1.1, messages=None, ):

    if messages is None:
        if system_prompt:
            messages = [{"role": "user", "content": system_prompt + text_input}]
        else:
            messages = [{"role": "user", "content": text_input}]
    else:
        messages.append({"role": "user", "content": text_input})

    text_input = tokenizer.apply_chat_template(
        messages, 
        tokenize=False, 
        add_generation_prompt=True
    )

    inputs = tokenizer([text_input], add_special_tokens=False, return_tensors='pt').to(device)

    with torch.no_grad():
        outputs = model.generate(
            **inputs, 
            max_new_tokens=max_new_tokens,
            temperature=temperature,
            num_beams=num_beams,
            top_k=top_k,
            do_sample=do_sample,
            top_p=top_p,
            eos_token_id=eos_token_id,
            num_return_sequences=num_return_sequences, 
            repetition_penalty=repetition_penalty,
        )

    outputs = outputs[:, inputs["input_ids"].shape[1]:]

    return tokenizer.batch_decode(outputs.detach().cpu().numpy(), skip_special_tokens=True), messages            

def load_model(model_name, chat_template=None, compile_mode=None,
               attn_implementation="flash_attention_2", quant=False):
    
    if quant:
        bnb_config4bit = BitsAndBytesConfig(
            load_in_4bit=True,
            bnb_4bit_quant_type="nf4",
            bnb_4bit_compute_dtype=torch.bfloat16,
            bnb_4bit_use_double_quant=True,
        )
        model = AutoModelForCausalLM.from_pretrained(
            model_name,
            trust_remote_code=True,
            use_cache=False,
            quantization_config=bnb_config4bit,
            device_map="auto",
            torch_dtype=torch.bfloat16,
            attn_implementation=attn_implementation,
        )
    else:
        model = AutoModelForCausalLM.from_pretrained(
            model_name,
            trust_remote_code=True,
            use_cache=False,
            device_map="auto",
            torch_dtype=torch.bfloat16,
            attn_implementation=attn_implementation,
        )

    if compile_mode:
        model.generation_config.cache_implementation = "static"
        model.forward = torch.compile(model.forward, mode=compile_mode, fullgraph=True)

    tokenizer = AutoTokenizer.from_pretrained(
        model_name, 
        trust_remote_code=True,
        add_bos_token=False
    )

    if chat_template:
        tokenizer.chat_template = chat_template

    return model, tokenizer

Chat template

The model uses the ChatML template, as so (with <|im_end|> as end token):

messages = [
    {"role": "system", "content": "You are a biomaterials scientist."},
    {"role": "user", "content": "What is the role of collagen in bone?"},
    {"role": "assistant", "content": "Collagen is a key structural protein."},
]
prompt = tokenizer.apply_chat_template(
        messages, 
        tokenize=False, 
        add_generation_prompt=True
)
print (prompt)

The output:

<|begin_of_text|><|im_start|>system
You are a biomaterials scientist.<|im_end|>
<|im_start|>user
What is the role of collagen in bone?<|im_end|>
<|im_start|>assistant
Collagen is a key structural protein.<|im_end|>
<|im_start|>assistant

Example use case

Load the model:

model, tokenizer,=load_model (model_name='lamm-mit/Bioinspired-SmolLM-1.7B-Instruct')

Collagen and the Glass Bead Game

messages=[]
result,messages=generate_response (model, tokenizer, text_input="Collagen and the Glass Bead Game, discuss their relationship.",
                                   num_return_sequences=1,  temperature=0.3,max_new_tokens=1024 , messages=[]
                                   system_prompt="You are materials scientist. ",)

for res in result:
    print(res, "\n")

messages.append (  {"role": "assistant", "content":result[0]})  

You can ask a follow-up question like so:

result,messages=generate_response (model, tokenizer, text_input="Summarize the key points in JSON format.",num_return_sequences=1, 
                                   temperature=0.3,max_new_tokens=1024 , messages=messages)

for res in result:
    print(res, "\n")

messages.append (  {"role": "assistant", "content":result[0]})

<pre style="white-space: pre-wrap;">

Here's a summary of collagen and the Glass Bead Game in JSON format:

```json
{
  "collagen": {
    "structure": "proteinous fibrous network",
    "composition": "glycoprotein",
    "properties": "high tensile strength, low stiffness",
    "functions": "structural support, cell signaling, wound healing",
    "types": ["alpha", "beta", "gamma", "delta"]
  },
  "glass bead game": {
    "rules": "a strategy game where players collect and trade glass beads, simulating the process of collagen synthesis and mineralization",
    "components": ["glass beads", "mineral deposits", "cell signaling molecules", "growth factors"],
    "goal": "collect and trade the most beads to achieve mineralization and growth",
    "rules of play": "players must collect beads, deposit them in cells, and stimulate mineralization through signaling molecules and growth factors",
    "game mechanics": "players earn points for successful mineralization, trade beads for resources, and manage their cells' mineralization and growth rates"
  },
}

In this JSON representation, collagen is a proteinous fibrous network with a high tensile strength and low stiffness, while the Glass Bead Game is a strategy game where players collect and trade glass beads to simulate the process of collagen synthesis and mineralization. The Glass Bead Game components include glass beads, mineral deposits, cell signaling molecules, and growth factors, with the goal of collecting and trading the most beads to achieve mineralization and growth. The rules of play involve collecting beads, depositing them in cells, and stimulating mineralization through signaling molecules and growth factors.

Benchmark

Performance on the bioinspired benchmark (testing with domain questions to assess performance relative to the training corpus around biological materials and spider silk):

image/png

Citation

Please cite as:

@article{LuLuuBuehler2024,
  title={Fine-tuning large language models for domain adaptation: Exploration of training strategies, scaling, model merging and synergistic capabilities},
  author={Wei Lu and Rachel K. Luu and Markus J. Buehler},
  journal={arXiv: https://arxiv.org/abs/2409.03444},
  year={2024},
}

@article{LuuBuehler2023bioinspiredLLM,
  title={BioinspiredLLM: Conversational Large Language Model for the Mechanics of Biological and Bio-Inspired Materials},
  author={Rachel K. Luu and Markus J. Buehler},
  year={2023},
  journal={Advanced Science},
  doi={10.1002/advs.202306724},
  eprint={2309.08788},
  archivePrefix={arXiv},
  primaryClass={cs.LG},
  url={https://arxiv.org/abs/2309.08788}
}

@article{Buehler2024XLoRA,
  title={X-LoRA: Mixture of low-rank adapter experts, a flexible framework for large language models with applications in protein mechanics and molecular design},
  author={Eric L. Buehler and Markus J. Buehler},
  year={2024},
  journal={APL Machine Learning},
  volume={2},
  number={2},
  pages={026119},
  doi={10.1063/5.0203126},
  note={\url{https://doi.org/10.1063/5.0203126}}
}

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · transformers

Можно запустить

Подбираем GPU…

Класс архитектуры
LlamaForCausalLM
Ревизия весов
e1d9256

0 моделей