/ Модель

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

Контекст
2 048 токенов
Параметры
5,2 млрд
Размер весов
8,1 ГБ
Лицензия
Apache 2.0
Архитектура
phi · dense
Библиотека
transformers
Опубликована
30 янв 2024

phi-2-upscaled-4B-instruct-v0.1

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

Экспериментальная чат-модель на базе Phi-2 с увеличенной глубиной предназначена для генерации текста и ответов на инструкции.

280скачиваний за 30 дней3лайкавеса обновлены9 фев 2024

Бенчмарки

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

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

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

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

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

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

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

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

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

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

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

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

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

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

daekeun-ml/phi-2-upscaled-4B-instruct-v0.1 — экспериментальная разговорная языковая модель на архитектуре Phi, созданная автором репозитория методом увеличения глубины (DUS): число трансформерных блоков Phi-2 увеличено с 32 до 48, затем проведено дополнительное предобучение и настройка инструкций. В метаданных указано 5,2 млрд параметров, контекст — до 2048 токенов; модель работает с текстом и использует шаблон диалога ChatML.

Модель предназначена для генерации текста и ответов на инструкции в чат-сценариях, а также для личных экспериментов и проверки концепций. Дополнительное предобучение выполнялось на выборке Wikipedia, настройка инструкций — на выборке OpenOrca, а выравнивание — на Intel/orca_dpo_pairs. Модель выпущена под лицензией Apache-2.0.

Автор предупреждает, что наборы данных для эксперимента были небольшими, качество не гарантируется, а отдельная проверка модели не проводилась. Для результатов обучения использовались QLoRA при настройке инструкций и выравнивании.

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

  • ответы на текстовые инструкции в чате
  • генерация продолжений текста
  • создание прототипа чат-бота
  • эксперименты с увеличением глубины языковой модели

Ограничения

Автор сообщает, что обучение проводилось на небольших выборках, поэтому качество не гарантируется; отдельная проверка модели не выполнялась. Контекст модели ограничен 2048 токенами.

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

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

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

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

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

Открыть на Hugging Face

phi-2-upscaled-4B-instruct-v0.1

Model Details

This model is a model that performed continued pre-training and fine-tuning (instruction tuning) using the depth up-scaling (DUS) technique disclosed by Upstage.

DUS(Depth Up-Scaling) and continued pre-training

Similar to the methodology disclosed in the paper, we expanded from 32 transformer blocks to 48 blocks and then continued pre-training with the public dataset. Pre-training was performed for 3 days using 4 ml.g5.48xlarge instances from AWS (NVIDIA A10G GPU x 32ea). For pre-training, we used a sample set from Wikipedia. Note that performance is not guaranteed since only a small number of datasets were used for the experiment. The number of samples for training set is just around 1.5 million after tokenization. For distributed training, all weights were trained without adapter techniques, and sharding parallelization was performed with ZeRO-2. The presets are as follows.

{
    "fp16": {
        "enabled": "auto",
        "loss_scale": 0,
        "loss_scale_window": 1000,
        "initial_scale_power": 16,
        "hysteresis": 2,
        "min_loss_scale": 1
    },
    
    "bf16": {
        "enabled": "auto"
    },    

    "optimizer": {
        "type": "AdamW",
        "params": {
            "lr": "auto",
            "betas": "auto",
            "eps": "auto",
            "weight_decay": "auto"
        }
    },

    "scheduler": {
        "type": "WarmupLR",
        "params": {
            "warmup_min_lr": "auto",
            "warmup_max_lr": "auto",
            "warmup_num_steps": "auto"
        }
    },

    "zero_optimization": {
        "stage": 2,
        "allgather_partitions": true,
        "allgather_bucket_size": 2e8,
        "overlap_comm": true,
        "reduce_scatter": true,
        "reduce_bucket_size": 2e8,
        "contiguous_gradients": true,
        "cpu_offload": true
    },

    "gradient_accumulation_steps": "auto",
    "gradient_clipping": "auto",
    "train_batch_size": "auto",
    "train_micro_batch_size_per_gpu": "auto"
}

Some hyperparameters are listed below.

batch_size: 2
num_epochs: 1
learning_rate: 3e-4
gradient_accumulation_steps: 8
lr_scheduler_type: "linear"
group_by_length: False

Fine-tuning

After performing pre-training, instruction tuning and alignment tuning were performed sequentially. This process only took about 10 hours using AWS ml.g5.24xlarge (NVIDIA A10G GPU x 4ea). The dataset used for instruction tuning is a sample set of the OpenOrca dataset, and the dataset used for alignment tuning is Intel's orca_dpo_pairs dataset. All fine-tuning was learned using QLoRA, and the batch sizes were set to 3 and 1, respectively. We used 1,024 for the context length. 2,048 is also possible, but applying DPO often runs out of memory on 24GB GPU memory, so we settled on 1,024. Please see below for relevant code snippets.

peft_config = LoraConfig(
    r=8,
    lora_alpha=16,
    target_modules=["q_proj", "k_proj", "v_proj", "fc1", "fc2"],
    lora_dropout=0.05,
    bias="none",
    task_type="CAUSAL_LM",
)
training_arguments = TrainingArguments(
    output_dir="logs",
    num_train_epochs=1,
    per_device_train_batch_size=batch_size,
    gradient_accumulation_steps=4,
    optim="paged_adamw_8bit",
    learning_rate=3e-4,
    weight_decay=0.001,
    bf16=True,
    max_grad_norm=0.3,
    max_steps=-1,
    warmup_ratio=0.03,
    group_by_length=True,
    lr_scheduler_type="cosine",
    report_to="wandb", ...
)

References

How to Get Started with the Model

Since this model used ChatGPT's ChatML template, <im_start> and <im_end> tokens were added. You can use Hugging Face's chat template to create the prompt, but you can also create the prompt yourself with the code snippet below.

def create_inference_prompt(text):
     string = f"""<|im_start|>system
You are a helpful AI assistant.<|im_end|>
<|im_start|>user
{text}<|im_end|>
<|im_start|>assistant
"""
     return string

If you want to simply see the inference results, please use the code snippet below.

from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
import torch
torch.set_default_device("cuda")
model_path = "daekeun-ml/phi-2-upscaled-4B-instruct-v0.1"

model = AutoModelForCausalLM.from_pretrained(
    model_path,
    torch_dtype="auto",
    trust_remote_code=True)

tokenizer = AutoTokenizer.from_pretrained(
    model_path, 
    use_fast=True, 
    trust_remote_code=True
)

# Format prompt
message = [
    {"role": "system", "content": "You are a helpful AI assistant. Generate appropriate answers to given questions."},
    {"role": "user", "content": "What is a Large Language Model?"}
]

prompt = tokenizer.apply_chat_template(message, add_generation_prompt=True, tokenize=False)
inputs = tokenizer(prompt, return_tensors="pt", return_attention_mask=False)

outputs = model.generate(**inputs, max_new_tokens=200, do_sample=True, top_p=0.9, temperature=0.5, repetition_penalty=1.2)
text = tokenizer.batch_decode(outputs)[0]
print(text)

Notes

License

Apache 2.0; The license of phi-2 is MIT, but the license of the orca dataset used for training is apache 2.0.

Caution

This model was created as a personal experiment, unrelated to the organization I work for. The model may not operate correctly because separate verification was not performed. Please be careful unless it is for personal experimentation or PoC (Proof of Concept)!

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

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

GPU в ailist

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

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

Подбираем GPU…

Класс архитектуры
PhiForCausalLM
Ревизия весов
145e71f

0 моделей