Text Generation
Transformers
Safetensors
Spanish
gemma
Legal
Law
Peru
Leyes Juridicas
conversational
text-generation-inference
Inference Endpoints
File size: 12,143 Bytes
cd42519
24e07b4
 
 
cd42519
24e07b4
 
 
 
 
 
03f4f2c
24e07b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd42519
 
24e07b4
cd42519
65093a4
 
24e07b4
 
 
cd42519
 
24e07b4
cd42519
24e07b4
 
 
 
 
 
 
 
 
 
 
 
6eaf1af
cd42519
 
 
24e07b4
cd42519
24e07b4
cd42519
24e07b4
 
 
 
 
cd42519
 
 
24e07b4
cd42519
24e07b4
cd42519
24e07b4
cd42519
24e07b4
 
cd42519
24e07b4
 
 
 
cd42519
24e07b4
 
 
 
 
 
cd42519
24e07b4
cd42519
24e07b4
 
cd42519
 
24e07b4
 
 
 
cd42519
6eaf1af
24e07b4
 
 
 
cd42519
 
24e07b4
cd42519
24e07b4
 
 
 
 
 
cd42519
24e07b4
cd42519
24e07b4
cd42519
24e07b4
 
 
 
 
 
 
 
 
cd42519
24e07b4
 
 
 
 
 
 
13b4e5e
24e07b4
 
 
 
 
 
 
 
 
 
cd42519
24e07b4
cd42519
 
6eaf1af
cd42519
24e07b4
cd42519
 
6eaf1af
cd42519
24e07b4
6eaf1af
13b4e5e
 
 
 
 
 
 
 
 
 
 
 
 
 
6eaf1af
 
 
cd42519
24e07b4
cd42519
24e07b4
 
2ade16c
 
cd42519
 
24e07b4
cd42519
24e07b4
cd42519
24e07b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd42519
24e07b4
cd42519
24e07b4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
---
language:
- es
license: apache-2.0
library_name: transformers
tags:
- Legal
- Law
- Peru
- Leyes Juridicas
datasets:
- somosnlp/constitucion-politica-del-peru-1993-qa
- somosnlp/constitucion-politica-del-peru-1993-qa-gemma-2b-it-format
- daqc/constitucion-politica-del-peru-1993-qa
widget:
- text: 'Una mujer es víctima de violencia de género y busca protección legal. ¿Qué
    debo hacer y bajo qué base legal debería actuar?

    '
- text: 'Un ciudadano es arrestado sin que se le informen sus derechos. ¿Qué capítulo
    y artículo de la Constitución del Perú establece los derechos fundamentales de
    las personas detenidas y las garantías procesales que deben respetarse durante
    su arresto?

    '
- text: 'Me gustaría solicitar asistencia legal gratuita en Perú. ¿Podrías proporcionarme
    los pasos necesarios para llevar a cabo este proceso?

    '
- text: ¿Qué artículo de la Constitución Política del Perú establece que toda persona
    tiene derecho a la vida, a su identidad, a su integridad moral, psíquica y física,
    y a su libre desarrollo y bienestar?
---

# Model Card for kuntur-peru-legal-es-gemma-2b-it-merged ⚖️

The kuntur-peru-legal-es-gemma-2b-it-merged model is a state-of-the-art language model fine-tuned specifically for legal text comprehension and generation tasks in Spanish, focusing on the legal context of the Peruvian Constitution. Leveraging advanced techniques such as Low-Rank Adaptation (LoRA) and Bits and Bytes Quantization (BNB), this model provides accurate and contextually relevant responses to legal queries, making it a valuable tool for legal professionals, researchers, and AI enthusiasts interested in the legal domain.

<p align="center">
  <img src="https://cdn-uploads.huggingface.co/production/uploads/64461026e1fd8d65b27e6187/L3eQBj1eJBB02B2V7fBex.jpeg" alt="Model Illustration" width="350">
</p>


## Table of Contents

- [kuntur-peru-legal-es-gemma-2b-it-merged ⚖️](#kuntur-peru-legal-es-gemma-2b-it-merged)
    + [Model Description 📘](#model-description)
  * [Finetuning Progress 🛠️](#finetuning-progress)
    + [Recommendations 📝](#recommendations-)
  * [How to Get Started with the Model 🚀](#how-to-get-started-with-the-model)
  * [Training Dataset 🧠](#training-dataset)
  * [Finetuning Progress 🤖](#finetuning-progress)
  * 
    + [Environment and Libraries 🖥️](#environment-and-libraries)
    + [QLoRA Configuration 🧮](#qlora-configuration)
    + [Model Merging and Saving 💾](#model-merging-and-saving)
  * [Logging with Wandb 📊](#logging-with-wandb)
  * [Environmental impact 🌳](#environmental-impac)



## Model Description

kuntur-peru-legal-es-gemma-2b-it-merged  is a contextual legal language model designed to provide personalized legal advice in Spanish based on Peruvian legal texts. Leveraging advanced techniques like LoRA, the model offers accurate and contextually relevant responses to legal queries, covering various aspects of Peruvian law and regulation. Whether it's understanding rights, navigating legal procedures, or interpreting statutes, kuntur-peru-legal-es-gemma-2b-it-merged empowers users with comprehensive and reliable legal guidance tailored to the Peruvian legal landscape.

- **Developed by:** [Alonso Quispe](https://huggingface.co/daqc)
- **Model type:** Causal Language Model, specially fine-tuned with LoRA for the distinct domain of Peruvian law and regulation.
- **Language(s) (NLP):** Spanish, tailored for the legal and regulatory context of Peru.
- **License:** Apache License. This open-source license ensures that the model can be freely used, modified, and distributed. Please check the model's page on Hugging Face for specific licensing details.
- **Base model:** google/gemma-2b-it`



## Recommendations

Users should verify model outputs against current regulations and consult with professionals for critical applications. Awareness of the model's scope and limitations is crucial for effective use.

# How to Get Started with the Model

```python
from transformers import AutoModelForCausalLM, AutoTokenizer

# Cargar el modelo y el tokenizador
model_name = "somosnlp/kuntur-peru-legal-es-gemma-2b-it-merged"
model = AutoModelForCausalLM.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)

# Ejemplo de uso
input_text = "Una persona ha sido despedida de su trabajo injustamente y necesita entender cuáles son sus derechos laborales según la Constitución Política del Perú."
input_ids = tokenizer.encode(input_text, return_tensors="pt")
output = model.generate(input_ids, max_length=100, num_return_sequences=1, temperature=0.7)
print(tokenizer.decode(output[0], skip_special_tokens=True))
```

## Training Dataset

The kuntur-peru-legal-es-gemma-2b-it-merged model was fine-tuned exclusively on the "[Constitución Política del Perú](https://huggingface.co/datasets/daqc/constitucion-politica-del-peru-1993-qa) dataset available through Hugging Face Datasets. This dataset serves as a rich source of questions and answers pertaining to the legal framework outlined in the Peruvian Constitution.
The dataset encompasses a wide range of topics and provisions within the Peruvian Constitution, providing comprehensive coverage of constitutional principles, rights, and legal interpretations.


## Train Progress
<p align="center">
  <img src="https://cdn-uploads.huggingface.co/production/uploads/64461026e1fd8d65b27e6187/m3yAx86LN-xLEZ4Mz1ALQ.png" alt="Train Graph" width="900">
</p>

## Eval Progress
<p align="center">
  <img src="https://cdn-uploads.huggingface.co/production/uploads/64461026e1fd8d65b27e6187/nuk-TgiEH8IRDjmP6_luR.png" alt="Val Graph" width="900">
</p>
---


## Environment and Libraries

The training process was executed within a Python environment, utilizing essential libraries to facilitate various tasks:
- **transformers:** Used for loading and fine-tuning the model, providing a seamless interface for working with pre-trained language models.
- **datasets:** Employed for efficient handling and preprocessing of the training dataset, ensuring streamlined data pipelines.
- **torch:** Utilized as the primary deep learning framework to support model training and optimization.
- **peft:** Integrated for applying Low-Rank Adaptation (LoRA) techniques to the model, enabling efficient adaptation to specialized domains without compromising performance.
- **qlora:** Additionally utilized for further model adaptation, enhancing its ability to comprehend and generate responses specific to the legal context of the "Constitucióm Política del Perú" dataset.

## QLoRA Configuration

QLoRA (Quantization LoRA) was employed to optimize the model's computational efficiency and memory footprint while preserving its accuracy. Two configurations were utilized:

- **BitsAndBytesConfig:** This configuration enabled the model to load in 4-bit quantization, leveraging the nf4 quantization type with a torch.bfloat16 compute data type for enhanced efficiency during inference.
    ```python
        bnb_config = BitsAndBytesConfig(
        load_in_4bit=True,
        bnb_4bit_quant_type="nf4",
        bnb_4bit_compute_dtype=torch.bfloat16,
        bnb_4bit_use_double_quant=False,
    )
    ```

- **LoRAConfig:** This configuration applied Low-Rank Adaptation (LoRA) to the model, optimizing its parameters for the specific task of language modeling in the legal domain. Key parameters include:
    - **r:** Reduced to 8 from the default 32, controlling the rank of adaptation layers.
    - **lora_alpha:** Adjusted to 16 from the default 64, regulating the sparsity of adapted weights.
    - **target_modules:** Specified modules for adaptation, focusing on query, key, value, and output projection layers.
    - **bias:** Set to "none" to exclude bias terms from adaptation, simplifying the model architecture.
    - **lora_dropout:** Reduced to 0.025 from the default 0.05, controlling the dropout rate during adaptation.
    - **task_type:** Configured as "CAUSAL_LM" to indicate the task type of the language model.
      
    ```python
        config = LoraConfig(
        r=8,
        lora_alpha=16,
        target_modules=['q_proj', 'k_proj', 'v_proj', 'o_proj'],
        bias="none",
        lora_dropout=0.025,
        task_type="CAUSAL_LM",
    )
    ```

These configurations were crucial for optimizing the model's performance and resource utilization during training and inference, ensuring efficient deployment.


## Model Merging and Saving

After fine-tuning, the LoRA-adjusted weights were merged back with the base Gemma model to create the final kuntur-peru-legal-es-gemma-2b-it-merged. The model was then saved and made available through Hugging Face for easy access and further development.


## Logging with Wandb

During the training process, Wandb (Weights & Biases) was used for comprehensive logging and visualization of key metrics. Wandb's powerful tracking capabilities enabled real-time monitoring of training progress, evaluation metrics, and model performance. Through interactive dashboards and visualizations, Wandb facilitated deep insights into the training dynamics, allowing for efficient model optimization and debugging. This logging integration with Wandb enhances transparency, reproducibility, and collaboration among researchers and practitioners.
  
 - eval/loss:1.1386919021606443
 - eval/runtime:44.2153
 - eval/samples_per_second:8.707
 - eval/steps_per_second:8.707
 - train/epoch:49.62
 - train/global_step:4,850
 - train/grad_norm:3.5548949241638184
 - train/learning_rate:0
 - train/loss:0.8596
 - train/total_flos:236,149,029,419,876,350
 - train/train_loss:1.105836234535139
 - train/train_runtime:13,237.4947
 - train/train_samples_per_second:5.9
 - train/train_steps_per_second:0.366


## Environmental impact

The training of `kuntur-peru-legal-es-gemma-2b-it-merged` was conducted optimizing the computational expenditure required.

- **Hardware Type:** NVIDIA A10G GPU
- **Hours Utilized:** Approximately 4 hours
- **Energy Consumption:** Approximately 300 Wh
- **Estimated CO2 Emissions:** Approximately 368.75g


## To-Do List

## Dataset Generation, Human Feedback Review with Argilla, and Finetuning with the Following Legal Texts:

| **Dataset Generation** | **Human Feedback Review with Argilla** | **Model Finetuning** |
|-----------|-----------|-----------|
| ☑️ Constitution of Peru | ☑️ Constitution of Peru | ☑️ Constitution of Peru |
| 🔲 Penal Code | 🔲 Penal Code | 🔲 Penal Code |
| 🔲 Congress Regulation | 🔲 Congress Regulation | 🔲 Congress Regulation |
| 🔲 New Constitutional Procedural Code | 🔲 New Constitutional Procedural Code | 🔲 New Constitutional Procedural Code |
| 🔲 Civil Code | 🔲 Civil Code | 🔲 Civil Code |
| 🔲 (TUO) Civil Procedural Code | 🔲 (TUO) Civil Procedural Code | 🔲 (TUO) Civil Procedural Code |
| 🔲 Penal Procedural Code (D.L 638) | 🔲 Penal Procedural Code (D.L 638) | 🔲 Penal Procedural Code (D.L 638) |
| 🔲 New Penal Procedural Code (D.L 957) | 🔲 New Penal Procedural Code (D.L 957) | 🔲 New Penal Procedural Code (D.L 957) |
| 🔲 Penal Execution Code | 🔲 Penal Execution Code | 🔲 Penal Execution Code |
| 🔲 Military Police Penal Code | 🔲 Military Police Penal Code | 🔲 Military Police Penal Code |
| 🔲 Military Police Justice Code | 🔲 Military Police Justice Code | 🔲 Military Police Justice Code |
| 🔲 Children and Adolescents Code | 🔲 Children and Adolescents Code | 🔲 Children and Adolescents Code |
| 🔲 Adolescent Penal Responsibility Code | 🔲 Adolescent Penal Responsibility Code | 🔲 Adolescent Penal Responsibility Code |
| 🔲 Commercial Code | 🔲 Commercial Code | 🔲 Commercial Code |
| 🔲 Consumer Protection and Defense Code | 🔲 Consumer Protection and Defense Code | 🔲 Consumer Protection and Defense Code |
| 🔲 Tax Code (TUO) | 🔲 Tax Code (TUO) | 🔲 Tax Code (TUO) |
| 🔲 Criminal Procedure Code | 🔲 Criminal Procedure Code | 🔲 Criminal Procedure Code |

## License

This project is distributed under the Apache 2.0 license.