sentence-transformers pytorch safetensors camembert feature-extraction sentence-similarity fr dataset:maastrichtlawtech/lleqa arxiv:2309.17050 license:apache-2.0 autotrain_compatible text-embeddings-inference endpoints_compatible region:us
---
datasets:
- maastrichtlawtech/lleqa
language: fr
library_name: sentence-transformers
license: apache-2.0
metrics:
- recall
pipeline_tag: sentence-similarity
tags:
- feature-extraction
- sentence-similarity
inference: true
widget:
- source_sentence: Je reçois des confidences liées à mon emploi. Qu'est-ce que je
    risque si je viole le secret professionnel ?
  sentences:
  - 'Art. 1 : Les médecins, chirurgiens, officiers de santé, pharmaciens, sages-femmes
    et toutes autres personnes dépositaires, par état ou par profession, des secrets
    qu''on leur confie, qui, hors le cas où ils sont appelés à rendre témoignage en
    justice ou devant une commission d''enquête parlementaire et celui où la loi,
    le décret ou l''ordonnance les oblige ou les autoriseà faire connaître ces secrets,
    les auront révélés, seront punis d''un emprisonnement d''un an à trois ans et
    d''une amende de cent euros à mille euros ou d''une de ces peines seulement.'
  - 'Art. 2 : L''allocataire peut demander l''allocation de naissance à partir du
    sixième mois de la grossesse et en obtenir le paiement deux mois avant la date
    probable de la naissance mentionnée sur le certificat médical à joindre à la demande.L''allocation
    de naissance demandée conformément à l''alinéa 1er est due par la caisse d''allocations
    familiales, par l''autorité ou par l''établissement public qui serait compétent,
    selon le cas, pour payer les allocations familiales à la date à laquelle la demande
    de paiement anticipé est introduite.'
  - 'Art. 3 : La periode de maternité constitue une période de repos de douze semaines,
    ou de treize semainesen cas de naissance multiple, au cours de laquelle la titulaire
    ne peut exercer son activité professionnelle habituelle ni aucune autre activité
    professionnelle.'
  example_title: Secret professionnel
---

# distilcamembert-lleqa

This is a [sentence-transformers](https://www.SBERT.net) 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](https://huggingface.co/datasets/maastrichtlawtech/lleqa) dataset for legal information retrieval in **French**.

## Usage
***

#### Sentence-Transformers

Using this model becomes easy when you have [sentence-transformers](https://www.SBERT.net) installed:

```
pip install -U sentence-transformers
```

Then you can use the model like this:

```python
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](https://www.SBERT.net), 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.

```python
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@10 |   NDCG@10 |   MAP@10 |   R@10 |   R@100 |   R@500 |
|---------:|----------:|---------:|-------:|--------:|--------:|
|    36.67 |     37.24 |    29.26 |  52.95 |   78.07 |   90.17 |

## Training
***

#### Background

We utilize the [distilcamembert-base](https://huggingface.co/cmarkea/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)](https://huggingface.co/datasets/maastrichtlawtech/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

```bibtex
@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},
}
```
