This repository hosts the uOttawa model developed for Subtask B (Legal Natural Language Inference) in the LegalLens-2024 shared task. The task focuses on classifying relationships between legal texts, such as determining if a premise (e.g., a summary of a legal complaint) entails, contradicts, or is neutral with respect to a hypothesis (e.g., an online review).
Model Type: Transformer-based model combined with a Convolutional Neural Network (CNN)
Framework: PyTorch, Transformers library
Training Data: LegalLensNLI dataset provided by the LegalLens-2024 organizers
Architecture: Integration of RoBERTa (ynie/roberta-large-snli_mnli_fever_anli_R1_R2_R3-nli) with a custom CNN for keyword pattern detection
Use Case: Classifying relationships between legal documents for applications like legal case matching and automated reasoning
The model architecture consists of:
RoBERTa model: Responsible for capturing contextual information from the input text.
CNN model: Used for keyword detection, including an embedding layer and three convolutional layers with filter sizes (2, 3, 4).
Fully connected layer: Combines the outputs from RoBERTa and CNN for the final classification.
To use this model, clone this repository and make sure to have the following installed:
pip install torch
pip install transformersfrom openmind import AutoTokenizer, AutoModel, is_torch_npu_available
from openmind_hub import snapshot_download
import torch.nn.functional as F
from torch import Tensor
import openmind
import torch
import argparse
import time
# 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)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--model_name_or_path",
type=str,
help="Path to model",
default="jeffding/roberta_cnn_legal-openmind",
)
args = parser.parse_args()
return args
def main():
args = parse_args()
model_path = args.model_name_or_path
if is_torch_npu_available():
device = "npu:0"
else:
device = "cpu"
# Load model from HuggingFace Hub
tokenizer = AutoTokenizer.from_pretrained(model_path,trust_remote_code=True)
model = AutoModel.from_pretrained(model_path, trust_remote_code=True).to(device)
start_time = time.time()
sentences = ['如何更换花呗绑定银行卡', 'How to replace the Huabei bundled bank card']
# Tokenize sentences
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt').to(device)
# 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:")
print(sentence_embeddings)
end_time = time.time()
print(f"硬件环境:{device},推理执行时间:{end_time - start_time}秒")
if __name__ == "__main__":
main()Load the model and run inference using the Hugging Face Transformers library:
from transformers import AutoTokenizer, AutoModelForSequenceClassification
# Load the model and tokenizer
model = AutoModelForSequenceClassification.from_pretrained("nimamegh/roberta_cnn_legal")
tokenizer = AutoTokenizer.from_pretrained("nimamegh/roberta_cnn_legal")
# Example inputs
premise = "The cat is on the mat."
hypothesis = "The animal is on the mat."
inputs = tokenizer(premise, hypothesis, return_tensors='pt')
# Get predictions
outputs = model(**inputs)
predictions = outputs.logits.argmax(dim=-1)
# Print the prediction result
print("Predicted class:", predictions.item())
# Interpretation (optional)
label_map = {0: "Entailment", 1: "Neutral", 2: "Contradiction"}
print("Result:", label_map[predictions.item()])Learning Rate: 2e-5
Batch Size: 4 (train and evaluation)
Number of Epochs: 20
Weight Decay: 0.01
Optimizer: AdamW
Trainer Class: Used for fine-tuning with early stopping and warmup steps
The model was evaluated using an F1-score across multiple domains in the validation set:
Performance on Hidden Test Set: F1-score of 0.724, achieving 5th place in the LegalLens-2024 competition.
Comparison:
Falcon 7B: 81.02% (average across domains)
RoBERTa base: 71.02% (average)
uOttawa Model: 88.6% (average on validation)
@misc{meghdadi2024uottawalegallens2024transformerbasedclassification,
title={uOttawa at LegalLens-2024: Transformer-based Classification Experiments},
author={Nima Meghdadi and Diana Inkpen},
year={2024},
eprint={2410.21139},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2410.21139},
}