/ Модель

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

Контекст
514 токенов
Параметры
81,2 млн
Лицензия
Apache 2.0
Архитектура
camembert · dense
Библиотека
sentence-transformers
Опубликована
28 сен 2023

distilcamembert-lleqa

ЭмбеддингиТекст → embedding3 профессии

Франкоязычная модель эмбеддингов для семантического поиска юридических статей по вопросам на основе набора LLeQA.

71скачиваний за 30 дней3лайкавеса обновлены31 окт 2024

Бенчмарки

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

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

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

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

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

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

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

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

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

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

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

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

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

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

maastrichtlawtech/distilcamembert-lleqa — модель эмбеддингов на базе DistilCamemBERT, разработанная Maastricht Law and Tech Lab. Она преобразует предложения и абзацы на французском языке в плотные векторы размерностью 768 и дообучена на наборе LLeQA для поиска нормативных статей, релевантных юридическим вопросам. Модель подходит для семантического поиска и кластеризации; обучение на парах «вопрос—статья» использует контрастивную цель. В оценке на тестовой части LLeQA с 195 вопросами и корпусом из 27,9 тыс. статей показаны MRR@10 36,67 и Recall@500 90,17.

Модель содержит 81,2 млн параметров, построена на архитектуре CamemBERT и имеет контекстное окно 514 токенов. Доступна в форматах PyTorch и Safetensors. Она предназначена прежде всего для поиска по франкоязычным правовым материалам бельгийского законодательства; результаты оценки относятся к LLeQA и не гарантируют аналогичного качества на других корпусах. Лицензия — Apache-2.0.

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

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

Ограничения

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

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

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

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

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

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

Открыть на Hugging Face

distilcamembert-lleqa

This is a sentence-transformers model: it maps sentences & paragraphs to a 768 dimensional dense vector space and can be used for tasks like clustering or semantic search. The model was trained on the LLeQA dataset for legal information retrieval in French.

Usage


Sentence-Transformers

Using this model becomes easy when you have sentence-transformers installed:

pip install -U sentence-transformers

Then you can use the model like this:

from sentence_transformers import SentenceTransformer
sentences = ["This is an example sentence", "Each sentence is converted"]

model = SentenceTransformer('maastrichtlawtech/distilcamembert-lleqa')
embeddings = model.encode(sentences)
print(embeddings)

🤗 Transformers

Without sentence-transformers, you can use the model like this: First, you pass your input through the transformer model, then you have to apply the right pooling-operation on-top of the contextualized word embeddings.

from transformers import AutoTokenizer, AutoModel
import torch


#Mean Pooling - Take attention mask into account for correct averaging
def mean_pooling(model_output, attention_mask):
    token_embeddings = model_output[0] #First element of model_output contains all token embeddings
    input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
    return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)

# Sentences we want sentence embeddings for
sentences = ['This is an example sentence', 'Each sentence is converted']

# Load model from HuggingFace Hub
tokenizer = AutoTokenizer.from_pretrained('maastrichtlawtech/distilcamembert-lleqa')
model = AutoModel.from_pretrained('maastrichtlawtech/distilcamembert-lleqa')

# Tokenize sentences
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')

# Compute token embeddings
with torch.no_grad():
    model_output = model(**encoded_input)

# Perform pooling. In this case, mean pooling.
sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
print(sentence_embeddings)

Evaluation


We evaluate the model on the test set of LLeQA, which consists of 195 legal questions with a knowlegde corpus of 27.9K candidate articles. We report the mean reciprocal rank (MRR), normalized discounted cumulative gainand (NDCG), mean average precision (MAP), and recall at various cut-offs (R@k).

MRR@10NDCG@10MAP@10R@10R@100R@500
36.6737.2429.2652.9578.0790.17

Training


Background

We utilize the distilcamembert-base model and fine-tuned it on 9.3K question-article pairs in French. We used a contrastive learning objective: given a short legal question, the model should predict which out of a set of sampled legal articles, was actually paired with it in the dataset. Formally, we compute the cosine similarity from each possible pairs from the batch. We then apply the cross entropy loss with a temperature of 0.05 by comparing with true pairs.

Hyperparameters

We trained the model on a single Tesla V100 GPU with 32GBs of memory during 20 epochs (i.e., 5.4k steps) using a batch size of 32. We used the AdamW optimizer with an initial learning rate of 2e-05, weight decay of 0.01, learning rate warmup over the first 50 steps, and linear decay of the learning rate. The sequence length was limited to 384 tokens.

Data

We use the Long-form Legal Question Answering (LLeQA) dataset to fine-tune the model. LLeQA is a French native dataset for studying legal information retrieval and question answering. It consists of a knowledge corpus of 27,941 statutory articles collected from the Belgian legislation, and 1,868 legal questions posed by Belgian citizens and labeled by experienced jurists with a comprehensive answer rooted in relevant articles from the corpus.

Citation

@article{louis2023interpretable,
  author = {Louis, Antoine and van Dijck, Gijs and Spanakis, Gerasimos},
  title = {Interpretable Long-Form Legal Question Answering with Retrieval-Augmented Large Language Models},
  journal = {CoRR},
  volume = {abs/2309.17050},
  year = {2023},
  url = {https://arxiv.org/abs/2309.17050},
  eprinttype = {arXiv},
  eprint = {2309.17050},
}

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

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

GPU в ailist

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

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

Подбираем GPU…

Класс архитектуры
CamembertModel
Ревизия весов
40fe7ff

0 моделей