/ Модель

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

Контекст
4 096 токенов
Параметры
1,6 млрд
Лицензия
Apache 2.0
Архитектура
zhinao · dense
Библиотека
transformers
Опубликована
20 мая 2024

360Zhinao-1.8B-Reranking

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

Авторегрессионная модель Qihoo 360 на 1,6 млрд параметров для оценки релевантности и ранжирования китайских текстов, в том числе в поиске и RAG.

117скачиваний за 30 дней4лайкавеса обновлены24 мая 2024

Бенчмарки

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

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

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

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

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

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

360Zhinao-1.8B-Reranking — плотная авторегрессионная модель семейства 360Zhinao, разработанная Qihoo 360 на базе собственной модели 360Zhinao-1.8b-Base. Она предназначена для ранжирования текстовых пар: оценивает релевантность документов запросу и помогает переставлять результаты поиска или фрагменты контекста в RAG-системе. В README сообщается о среднем результате 70,13 на китайском бенчмарке MTEB Chinese Reranking и первом месте среди открытых моделей на момент публикации карточки.

Модель содержит 1,6 млрд параметров, принимает текст и имеет контекстное окно 4096 токенов. Обучение проводилось на четырёх наборах данных бенчмарка; разработчики описывают работу по согласованию задач и стабилизации обучения. Репозиторий содержит веса PyTorch, библиотека — Transformers. Лицензия Apache-2.0.

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

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

Ограничения

README описывает оценку на четырёх наборах китайского бенчмарка; результаты для других языков и доменов не приведены. Контекст ограничен 4096 токенами.

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

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

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

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

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

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

Открыть на Hugging Face

MTEB Leaderboard Chinese Reranking Results

We have validated the performance of our model on the mteb-chinese-reranking leaderboard. Currently, the open-source models on this leaderboard are primarily bidirectional discriminative models (BERT-like models). The only unidirectional generative model (GPT-like model) is gte-Qwen1.5-7B-instruct, which has an average score of 66.38, ranking 25th, with less than ideal results. Our self-developed unidirectional generative model, 360Zhinao-1.8B-reranking, achieved an average score of 70.13, currently ranking first overall and first among open-source models, opening up new possibilities for generative models to undertake discriminative tasks. For more detail, please check 360zhinao.

ModelT2RerankingMMarcoRerankingCMedQAv1CMedQAv2Avg
360Zhinao-1.8B-Reranking68.5537.2986.7587.9270.13
piccolo-large-zh-v267.1533.3990.1489.3170
Baichuan-text-embedding67.8534.388.4688.0669.67
stella-mrl-large-zh-v3.5-1792d66.4328.8589.1889.3368.45
PEG69.4333.5586.5684.0968.41
bge-reranker-base67.2835.4681.2784.167.03
bge-reranker-large67.637.1782.1484.1967.78

Requirements

pip install -r requirements.txt

If your GPU supports fp16 or bf16 precision, we also recommend installing flash-attention (now with support for flash attention 2) to improve your runtime efficiency and reduce memory usage. (flash-attention is optional and not required for running this project)

git clone https://github.com/Dao-AILab/flash-attention
cd flash-attention && pip install .
# The installation below is optional and might be slow.
# pip install csrc/layer_norm
# No need to install the following if the flash-attn version is above 2.1.1.
# pip install csrc/rotary

You can also use the following command to install flash-attention.

FLASH_ATTENTION_FORCE_BUILD=TRUE ./miniconda3/bin/python -m pip install flash-attn==2.3.6

Model Introduction

The 360Zhinao-1.8B-Reranking model utilizes the self-developed 360Zhinao-1.8b-Base model as its foundation. Through iterative discovery and resolution of the following technical issues, it continuously stimulates the world knowledge inherent in the large model during the pre-training phase, better bridging the gap between generative models and discriminative tasks.

Data Processing

The model training did not utilize world knowledge, meaning it neither continue pre-training with domain-specific data nor fine-tuned datasets outside of the four datasets on the leaderboard. It only used the four datasets within the leaderboard, carefully iterating through data perception, data cleaning and data mining to ensure that the ranking in individual tasks could reach the top three level.

Resolving Task Conflicts and Catastrophic Forgetting

When merging four tasks, due to different data domain distributions, answer patterns, training data volumes, convergence steps, and even sequence lengths, conflicts exist between different tasks. Deeply resolving these conflict issues is crucial to obtaining a universal model with the best comprehensive indicators across different tasks.

Resolving Training Instability

Unlike generative tasks that produce multiple characters, using generative models for discriminative tasks requires the model to output a continuous value. Therefore, there is an oscillation problem during the training process. Deeply analyzing and resolving training instability can result in a model with better generalization and robustness.

Inference Script

You can copy the following scripts to mteb-eval-scripts, then replace FlagReranker with FlagRerankerCustom in eval_cross_encoder scripts, then run eval_cross_encoder to reproduce our complete performance on the mteb-chinese-reranking leaderboard.

from typing import cast, List, Union, Tuple, Dict, Optional

import numpy as np
import torch
from tqdm import tqdm
from transformers import AutoModel, AutoTokenizer, AutoModelForSequenceClassification
import transformers
from transformers.trainer_pt_utils import LabelSmoother
IGNORE_TOKEN_ID = LabelSmoother.ignore_index

def preprocess(
    sources,
    tokenizer: transformers.PreTrainedTokenizer,
    max_len: int = 1024,
    system_message: str = "",
    device = None,
) -> Dict:
    roles = {"user": "<|im_start|>user", "assistant": "<|im_start|>assistant"}
    answer_len = 64

    im_start = tokenizer.im_start_id
    im_end = tokenizer.im_end_id
    nl_tokens = tokenizer('\n').input_ids
    _system = tokenizer('system').input_ids + nl_tokens
    _user = tokenizer('user').input_ids + nl_tokens
    _assistant = tokenizer('assistant').input_ids + nl_tokens

    # Apply prompt templates
    input_ids, targets = [], []
    for i, source in enumerate(sources):
        ## system_message
        input_id, target = [], []
        system = [im_start] + _system + tokenizer(system_message, max_length=max_len-answer_len, truncation=True).input_ids + [im_end] + nl_tokens
        input_id += system
        target += [im_start] + [IGNORE_TOKEN_ID] * (len(system)-3) + [im_end] + nl_tokens
        assert len(input_id) == len(target)
        
        ## query ans
        source = "\n\n".join(source)
        role = "<|im_start|>user"
        _input_id = tokenizer(role, max_length=max_len-answer_len, truncation=True).input_ids + nl_tokens + \
            tokenizer(source, max_length=max_len-answer_len, truncation=True).input_ids + [im_end] + nl_tokens
        input_id += _input_id
        if role == '<|im_start|>user':
            _target = [im_start] + [IGNORE_TOKEN_ID] * (len(_input_id)-3) + [im_end] + nl_tokens
        elif role == '<|im_start|>assistant':
            _target = [im_start] + [IGNORE_TOKEN_ID] * len(tokenizer(role, max_length=max_len-answer_len, truncation=True).input_ids) + \
                _input_id[len(tokenizer(role, max_length=max_len-answer_len, truncation=True).input_ids)+1:-2] + [im_end] + nl_tokens
        else:
            raise NotImplementedError
        target += _target

        ## label use placeholder 0; It will be masked later in the modeling_zhinao.py
        role = "<|im_start|>assistant"
        _input_id = tokenizer(role, max_length=max_len-answer_len, truncation=True).input_ids + nl_tokens + \
            tokenizer("0", max_length=max_len-answer_len, truncation=True).input_ids + [im_end] + nl_tokens
        input_id += _input_id
        if role == '<|im_start|>user':
            _target = [im_start] + [IGNORE_TOKEN_ID] * (len(_input_id)-3) + [im_end] + nl_tokens
        elif role == '<|im_start|>assistant':
            _target = [im_start] + [IGNORE_TOKEN_ID] * len(tokenizer(role, max_length=max_len-answer_len, truncation=True).input_ids) + \
                _input_id[len(tokenizer(role, max_length=max_len-answer_len, truncation=True).input_ids)+1:-2] + [im_end] + nl_tokens
        else:
            raise NotImplementedError
        target += _target

        assert len(input_id) == len(target)
        input_id += [tokenizer.pad_token_id] * (max_len - len(input_id))
        target += [IGNORE_TOKEN_ID] * (max_len - len(target))
        if len(input_id) > max_len:
            print("max_len_error")
            print(tokenizer.decode(input_id))

        input_ids.append(input_id[:max_len])
        targets.append(target[:max_len])
    input_ids = torch.tensor(input_ids, dtype=torch.int)
    targets = torch.tensor(targets, dtype=torch.int)
    #print(f"input_ids {input_ids.shape}")
    #print(f"targets {targets.shape}")

    return dict(
        input_ids=input_ids.to(device),
        labels=targets.to(device),
        attention_mask=input_ids.ne(tokenizer.pad_token_id).to(device),
    )

class FlagRerankerCustom:
    def __init__(
            self,
            model_name_or_path: str = None,
            use_fp16: bool = False
    ) -> None:
        self.tokenizer = transformers.AutoTokenizer.from_pretrained(
            model_name_or_path, 
            model_max_length=1024, 
            padding_side="right", 
            use_fast=False, 
            trust_remote_code=True
            )
        self.tokenizer.pad_token_id = self.tokenizer.eod_id
        config = transformers.AutoConfig.from_pretrained(
            model_name_or_path,
            trust_remote_code=True,
            bf16=True,
            )
        config.use_cache = False
        self.model = transformers.AutoModelForCausalLM.from_pretrained(
            model_name_or_path,
            config=config,
            trust_remote_code=True,
            )
        self.model.linear.bfloat16()

        if torch.cuda.is_available():
            self.device = torch.device('cuda')
        elif torch.backends.mps.is_available():
            self.device = torch.device('mps')
        else:
            self.device = torch.device('cpu')
            use_fp16 = False
        if use_fp16:
            self.model.half()

        self.model = self.model.to(self.device)

        self.model.eval()

        self.num_gpus = torch.cuda.device_count()
        if self.num_gpus > 1:
            print(f"----------using {self.num_gpus}*GPUs----------")
            self.model = torch.nn.DataParallel(self.model)

    @torch.no_grad()
    def compute_score(self, sentence_pairs: Union[List[Tuple[str, str]], Tuple[str, str]], batch_size: int =128,
                      max_length: int = 1024) -> List[float]:
        if self.num_gpus > 0:
            batch_size = batch_size * self.num_gpus

        assert isinstance(sentence_pairs, list)
        if isinstance(sentence_pairs[0], str):
            sentence_pairs = [sentence_pairs]

        all_scores = []
        for start_index in tqdm(range(0, len(sentence_pairs), batch_size), desc="Compute Scores",
                                disable=False):
            sentences_batch = sentence_pairs[start_index:start_index + batch_size] # [[q,ans],[q, ans]...]
            inputs = preprocess(sources=sentences_batch, tokenizer=self.tokenizer,max_len=1024,device=self.device)
            scores = self.model(**inputs, return_dict=True).logits.view(-1, ).float()
            all_scores.extend(scores.cpu().numpy().tolist())

        if len(all_scores) == 1:
            return all_scores[0]
        return all_scores


if __name__ == "__main__":
    model_name_or_path = "360Zhinao-1.8B-Reranking"
    model = FlagRerankerCustom(model_name_or_path, use_fp16=False)
    inputs=[["What Color Is the Sky","Blue"], ["What Color Is the Sky","Pink"],]
    ret = model.compute_score(inputs)
    print(ret)

License

The source code of this repository follows the open-source license Apache 2.0. 360​Zhinao open-source models support commercial use. If you wish to use these models or continue training them for commercial purposes, please contact us via email (g-zhinao-opensource@360.cn) to apply. For the specific license agreement, please see <<360 Zhinao Open-Source Model License>>.

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

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

GPU в ailist

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

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

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

Класс архитектуры
ZhinaoForCausalLM
Ревизия весов
37ca58e

0 моделей