/ Модель

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

Контекст
8 192 токена
Параметры
7,5 млрд
Размер весов
16,5 ГБ
Лицензия
Apache 2.0
Архитектура
ddllama · dense
Базовая модель
Meta-Llama-3-8B-Instruct
Библиотека
transformers
Опубликована
30 мар 2025

FlexiDepth-Llama-3-8B-Instruct

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

Дообученная английская модель на базе Llama 3 8B Instruct с динамическим пропуском слоёв для более эффективной генерации текста.

335скачиваний за 30 дней3лайкавеса обновлены17 окт 2025

Бенчмарки

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

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

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

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

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

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

FlexiDepth-Llama-3-8B-Instruct — диалоговая причинно-языковая модель, разработанная Xuan Luo, Weizhi Wang и Xifeng Yan. Это дообученная версия Meta Llama 3 8B Instruct с методом FlexiDepth, который динамически пропускает слои во время генерации текста, чтобы сократить вычисления и ускорить вывод. Архитектура — плотная DDLlamaForCausalLM; модель содержит 7,5 млрд параметров, принимает текст и имеет контекст до 8192 токенов.

Модель предназначена для генерации текста и ответов на инструкции на английском языке. Авторы приводят результаты по языковым и рассуждательным тестам: в опубликованном сравнении качество сопоставимо с базовой Llama 3 8B Instruct на большинстве заданий при меньшем среднем числе используемых слоёв. Подход также позволяет анализировать, сколько слоёв модель задействует для разных токенов и задач.

Модель распространяется в формате Safetensors под лицензией Apache-2.0. Для загрузки авторы указывают использование Transformers версии 4.57.0; заявленные результаты относятся к описанному в README оцениванию и не гарантируют такое же ускорение или качество в любой среде и на любых задачах.

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

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

Ограничения

Модель рассчитана на английский язык; README не сообщает о поддержке других языков. Фактическое ускорение и сохранение качества зависят от задач и среды выполнения, а результаты в карточке охватывают только указанные авторами бенчмарки.

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

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

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

Также подходит для

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

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

Открыть на Hugging Face

FlexiDepth-Llama-3-8B-Instruct

This model is the official implementation of the paper Adaptive Layer-skipping in Pre-trained LLMs. FlexiDepth-Llama-3-8B-Instruct is built on meta-llama/Meta-Llama-3-8B-Instruct and is trained to dynamically skip layers during inference, enabling significant speedups.

📰 News: We have updated our training method for improved results! For details about the updated training method and datasets, please refer to our GitHub repository: luoxuan-cs/Flexidepth.

📚 Resources

Notice that the current implementation uses transformers==4.57.0

Model Description

FlexiDepth-Llama-3-8B-Instruct is an enhanced version of the Llama-3-8B-Instruct model, incorporating the Flexidepth method to enable adaptive layer-skipping during text generation. This approach reveals unique layer allocation patterns, showing how computational demands vary across different tokens. The token depth map visualization (see below) demonstrates that summarization tasks typically require more layers than extractive question answering, while in mathematical reasoning tasks like addition, tokens on the left-hand side of equations use fewer layers than those on the right. For further insights, refer to the dataset at xuan-luo/FlexiPatterns-Llama-3-8B-Instruct.

  • Developed by: Xuan Luo, Weizhi Wang, Xifeng Yan
  • Model type: Causal Language Model with adaptive layer-skipping
  • Language(s) (NLP): English (en)
  • License: Apache-2.0
  • Finetuned from model: meta-llama/Meta-Llama-3-8B-Instruct

Get the number of layers used when generating different tokens

import transformers
from transformers import TextStreamer
import torch
from transformers.generation.streamers import BaseStreamer


class TokenStreamer(BaseStreamer):
    """
    Simple token streamer that prints each token with its corresponding layers used.
    
    Parameters:
        tokenizer (`AutoTokenizer`):
            The tokenizer used to decode the tokens.
        skip_prompt (`bool`, *optional*, defaults to `False`):
            Whether to skip the prompt tokens in the output. Useful for chatbots.
    """

    def __init__(self, tokenizer, skip_prompt=True):
        self.tokenizer = tokenizer
        self.skip_prompt = skip_prompt
        self.next_tokens_are_prompt = True

    def put(self, value):
        """
        Receives tokens and prints each one surrounded by brackets.
        """
        if len(value.shape) > 1 and value.shape[0] > 1:
            raise ValueError("TokenStreamer only supports batch size 1")
        elif len(value.shape) > 1:
            value = value[0]

        if self.skip_prompt and self.next_tokens_are_prompt:
            self.next_tokens_are_prompt = False
            return

        # Process each token in the received tensor
        for token_id in value.tolist():
            token_text = self.tokenizer.decode([token_id])
            print(f"={repr(token_text)}", end="\n", flush=True)

    def end(self):
        """Prints a newline at the end of generation."""
        self.next_tokens_are_prompt = True
        print()  # Print a newline at the end



# model path
model_id = "xuan-luo/FlexiDepth-Llama-3-8B-Instruct"
# tokenizer
tokenizer = transformers.AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
model = transformers.AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.bfloat16,
    device_map="auto",
    trust_remote_code=True
)

pipeline = transformers.pipeline(
    "text-generation",
    model=model,
    tokenizer=tokenizer,
    model_kwargs={"torch_dtype": torch.bfloat16},
    device_map="auto",
    trust_remote_code=True
)

messages = [
    {"role": "user", "content": \
"""
Please calcualte the sum of the eight numbers in the list: [99, 45, 12, 78, 33, 66, 21, 54]. Please solve this problem step by step.
"""},
]

terminators = [
    pipeline.tokenizer.eos_token_id,
    pipeline.tokenizer.convert_tokens_to_ids("<|eot_id|>")
]


streamer = TokenStreamer(tokenizer)
outputs = pipeline(
    messages,
    max_new_tokens=512,
    eos_token_id=terminators,
    do_sample=True,
    temperature=0.6,
    top_p=1.0,
    streamer=streamer,
)

Evaluation

The evaluation was conducted using the lm-eval-harness framework (version 0.4.9.1). This is an update from the version used in our original paper (v0.4.8). A key change in the newer framework is the introduction of the new humaneval_instruct benchmark, which is more suitable for instruction-tuned models. We have therefore included its results below.

All evaluation scripts and detailed results are available in the evals folder of this repository.

Performance Comparison

The table below compares FlexiDepth-Llama-3-8B-Instruct against the baseline Llama-3-8B-Instruct. For our model, we report both the performance score and the average number of layers used per task, demonstrating its efficiency.

BenchmarkShotsMetricFlexiDepth ScoreFlexiDepth Avg. LayersLlama-3 ScoreLlama-3 Layers
MMLU5acc0.664228.310.673232
Hellaswag5acc_norm0.745130.150.706632
Winogrande5acc0.754527.650.738032
GSM8K5strict-match0.701322.390.668732
HumanEval0pass@10.347622.970.292732
HumanEval-Instruct0pass@10.609822.180.597632
CoQA0f10.787825.170.781632

These results show that FlexiDepth-Llama-3-8B-Instruct maintains comparable or superior performance across most benchmarks while significantly reducing the average number of layers used for inference.

Model Card Authors

Xuan Luo, Weizhi Wang, Xifeng Yan

Model Card Contact

For questions or inquiries, please contact xuan_luo@ucsb.edu.

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

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

GPU в ailist

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

Нельзя запустить

Модели нужен код из репозитория; автор пока не в списке доверенных организаций.

Класс архитектуры
DDLlamaForCausalLM
Ревизия весов
2ce7359

0 моделей