MMR408 commited on
Commit
fa0a4cc
·
verified ·
1 Parent(s): b247955

Upload IVRIUS_finetune.ipynb with huggingface_hub

Browse files
Files changed (1) hide show
  1. IVRIUS_finetune.ipynb +338 -0
IVRIUS_finetune.ipynb ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": [],
7
+ "gpuType": "T4"
8
+ },
9
+ "kernelspec": {
10
+ "name": "python3",
11
+ "display_name": "Python 3"
12
+ },
13
+ "accelerator": "GPU"
14
+ },
15
+ "cells": [
16
+ {
17
+ "cell_type": "markdown",
18
+ "metadata": {},
19
+ "source": [
20
+ "# 🏛️ IVRIUS — Fine Tuning Jurídico Bilíngue\n",
21
+ "**Modelo:** Llama-3.1-8B + QLoRA (4-bit)\n",
22
+ "**Dataset:** STJ + TJMG + Pares BR↔US + CIJ\n",
23
+ "**Tempo estimado:** 1-2h no T4 Colab\n",
24
+ "\n",
25
+ "### ✅ Checklist antes de rodar:\n",
26
+ "- [ ] Runtime → Change runtime type → **T4 GPU**\n",
27
+ "- [ ] Conectado ao Colab\n",
28
+ "- [ ] Token HuggingFace disponível"
29
+ ]
30
+ },
31
+ {
32
+ "cell_type": "code",
33
+ "metadata": {},
34
+ "source": [
35
+ "# ── Célula 1: Instalar dependências ──────────────────────────────\n",
36
+ "!pip install -q \"unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git\"\n",
37
+ "!pip install -q --no-deps xformers trl peft accelerate bitsandbytes\n",
38
+ "!pip install -q datasets huggingface_hub\n",
39
+ "print('✅ Dependências instaladas!')"
40
+ ],
41
+ "execution_count": null,
42
+ "outputs": []
43
+ },
44
+ {
45
+ "cell_type": "code",
46
+ "metadata": {},
47
+ "source": [
48
+ "# ── Célula 2: Configuração ────────────────────────────────────────\n",
49
+ "HF_TOKEN = 'SEU_HF_TOKEN_AQUI'\n",
50
+ "HF_REPO_OUT = 'MMR408/ivrius-llama-juridico-v1' # onde salvar o modelo\n",
51
+ "MODEL_BASE = 'unsloth/llama-3.1-8b-bnb-4bit'\n",
52
+ "\n",
53
+ "import os\n",
54
+ "os.environ['HF_TOKEN'] = HF_TOKEN\n",
55
+ "\n",
56
+ "from huggingface_hub import login\n",
57
+ "login(token=HF_TOKEN)\n",
58
+ "print('✅ HuggingFace autenticado!')"
59
+ ],
60
+ "execution_count": null,
61
+ "outputs": []
62
+ },
63
+ {
64
+ "cell_type": "code",
65
+ "metadata": {},
66
+ "source": [
67
+ "# ── Célula 3: Carregar modelo base ───────────────────────────────\n",
68
+ "from unsloth import FastLanguageModel\n",
69
+ "import torch\n",
70
+ "\n",
71
+ "max_seq_length = 2048\n",
72
+ "dtype = None\n",
73
+ "load_in_4bit = True\n",
74
+ "\n",
75
+ "model, tokenizer = FastLanguageModel.from_pretrained(\n",
76
+ " model_name=MODEL_BASE,\n",
77
+ " max_seq_length=max_seq_length,\n",
78
+ " dtype=dtype,\n",
79
+ " load_in_4bit=load_in_4bit,\n",
80
+ " token=HF_TOKEN,\n",
81
+ ")\n",
82
+ "print('✅ Modelo base carregado!')"
83
+ ],
84
+ "execution_count": null,
85
+ "outputs": []
86
+ },
87
+ {
88
+ "cell_type": "code",
89
+ "metadata": {},
90
+ "source": [
91
+ "# ── Célula 4: Configurar LoRA ─────────────────────────────────────\n",
92
+ "model = FastLanguageModel.get_peft_model(\n",
93
+ " model,\n",
94
+ " r=16,\n",
95
+ " target_modules=['q_proj','k_proj','v_proj','o_proj',\n",
96
+ " 'gate_proj','up_proj','down_proj'],\n",
97
+ " lora_alpha=16,\n",
98
+ " lora_dropout=0,\n",
99
+ " bias='none',\n",
100
+ " use_gradient_checkpointing='unsloth',\n",
101
+ " random_state=42,\n",
102
+ ")\n",
103
+ "print('✅ LoRA configurado!')\n",
104
+ "model.print_trainable_parameters()"
105
+ ],
106
+ "execution_count": null,
107
+ "outputs": []
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "metadata": {},
112
+ "source": [
113
+ "# ── Célula 5: Preparar datasets ───────────────────────────────────\n",
114
+ "from datasets import load_dataset, Dataset, concatenate_datasets\n",
115
+ "import json\n",
116
+ "\n",
117
+ "ALPACA_PROMPT = \"\"\"Abaixo está uma instrução jurídica. Responda de forma precisa e fundamentada.\n",
118
+ "\n",
119
+ "### Instrução:\n",
120
+ "{instruction}\n",
121
+ "\n",
122
+ "### Resposta:\n",
123
+ "{response}\"\"\"\n",
124
+ "\n",
125
+ "EOS = tokenizer.eos_token\n",
126
+ "\n",
127
+ "def format_alpaca(examples):\n",
128
+ " texts = []\n",
129
+ " for inst, resp in zip(examples['instruction'], examples['response']):\n",
130
+ " texts.append(ALPACA_PROMPT.format(instruction=inst, response=resp) + EOS)\n",
131
+ " return {'text': texts}\n",
132
+ "\n",
133
+ "# ── Dataset 1: STJ ementas (resumo) ──────────────────────────────\n",
134
+ "print('📥 Carregando STJ...')\n",
135
+ "stj_raw = load_dataset('celsowm/jurisprudencias_stj', split='train[:2000]', token=HF_TOKEN)\n",
136
+ "\n",
137
+ "def stj_to_alpaca(row):\n",
138
+ " ementa = str(row.get('ementa_texto') or '').strip()[:500]\n",
139
+ " acordao = str(row.get('acordao') or '').strip()[:1000]\n",
140
+ " if not ementa or len(ementa) < 50:\n",
141
+ " return None\n",
142
+ " return {\n",
143
+ " 'instruction': f'Resuma a seguinte decisão jurídica do STJ ({row.get(\"identificacao\",\"\")}):\\n{acordao[:600] if acordao else ementa}',\n",
144
+ " 'response': ementa\n",
145
+ " }\n",
146
+ "\n",
147
+ "stj_items = [stj_to_alpaca(r) for r in stj_raw if stj_to_alpaca(r)]\n",
148
+ "ds_stj = Dataset.from_list(stj_items)\n",
149
+ "print(f'✅ STJ: {len(ds_stj)} exemplos')\n",
150
+ "\n",
151
+ "# ── Dataset 2: TJMG ementas ───────────────────────────────────────\n",
152
+ "print('📥 Carregando TJMG...')\n",
153
+ "tjmg_raw = load_dataset('celsowm/jurisprudencias_tjmg', split='train[:2000]', token=HF_TOKEN)\n",
154
+ "\n",
155
+ "def tjmg_to_alpaca(row):\n",
156
+ " ementa = str(row.get('ementa') or '').strip()[:500]\n",
157
+ " if not ementa or len(ementa) < 50:\n",
158
+ " return None\n",
159
+ " return {\n",
160
+ " 'instruction': f'Resuma a seguinte decisão jurídica do TJMG ({row.get(\"numero_processo\",\"\")}):\\n{ementa[:300]}',\n",
161
+ " 'response': ementa\n",
162
+ " }\n",
163
+ "\n",
164
+ "tjmg_items = [tjmg_to_alpaca(r) for r in tjmg_raw if tjmg_to_alpaca(r)]\n",
165
+ "ds_tjmg = Dataset.from_list(tjmg_items)\n",
166
+ "print(f'✅ TJMG: {len(ds_tjmg)} exemplos')\n",
167
+ "\n",
168
+ "# ── Dataset 3: Pares bilíngues BR↔US (do HuggingFace) ────────────\n",
169
+ "print('📥 Carregando pares bilíngues...')\n",
170
+ "ds_pairs_raw = load_dataset('MMR408/proejto2', split='train', token=HF_TOKEN)\n",
171
+ "\n",
172
+ "# Fallback: usar pares hardcoded se não encontrar\n",
173
+ "# (você pode subir o JSONL manualmente no Colab também)\n",
174
+ "pairs_items = []\n",
175
+ "for row in ds_pairs_raw:\n",
176
+ " prompt = str(row.get('prompt') or '')\n",
177
+ " response = str(row.get('response') or '')\n",
178
+ " if prompt and response and len(response) > 100:\n",
179
+ " pairs_items.append({'instruction': prompt, 'response': response})\n",
180
+ "\n",
181
+ "ds_pairs = Dataset.from_list(pairs_items) if pairs_items else Dataset.from_list([])\n",
182
+ "print(f'✅ Pares BR↔US: {len(ds_pairs)} exemplos')\n",
183
+ "\n",
184
+ "# ── Combinar todos ────────────────────────────────────────────────\n",
185
+ "datasets_list = [ds for ds in [ds_stj, ds_tjmg, ds_pairs] if len(ds) > 0]\n",
186
+ "ds_combined = concatenate_datasets(datasets_list).shuffle(seed=42)\n",
187
+ "print(f'\\n✅ Dataset combinado: {len(ds_combined)} exemplos totais')"
188
+ ],
189
+ "execution_count": null,
190
+ "outputs": []
191
+ },
192
+ {
193
+ "cell_type": "code",
194
+ "metadata": {},
195
+ "source": [
196
+ "# ── Célula 6: Tokenizar ───────────────────────────────────────────\n",
197
+ "ds_formatted = ds_combined.map(format_alpaca, batched=True,\n",
198
+ " remove_columns=ds_combined.column_names)\n",
199
+ "print(f'✅ Tokenizado: {len(ds_formatted)} exemplos')\n",
200
+ "print(f'\\nAmostra:\\n{ds_formatted[0][\"text\"][:300]}...')"
201
+ ],
202
+ "execution_count": null,
203
+ "outputs": []
204
+ },
205
+ {
206
+ "cell_type": "code",
207
+ "metadata": {},
208
+ "source": [
209
+ "# ── Célula 7: Treinar ─────────────────────────────────────────────\n",
210
+ "from trl import SFTTrainer\n",
211
+ "from transformers import TrainingArguments\n",
212
+ "from unsloth import is_bfloat16_supported\n",
213
+ "\n",
214
+ "trainer = SFTTrainer(\n",
215
+ " model=model,\n",
216
+ " tokenizer=tokenizer,\n",
217
+ " train_dataset=ds_formatted,\n",
218
+ " dataset_text_field='text',\n",
219
+ " max_seq_length=max_seq_length,\n",
220
+ " dataset_num_proc=2,\n",
221
+ " packing=False,\n",
222
+ " args=TrainingArguments(\n",
223
+ " per_device_train_batch_size=2,\n",
224
+ " gradient_accumulation_steps=4,\n",
225
+ " warmup_steps=10,\n",
226
+ " max_steps=120, # ~1.5h no T4 — aumente para 300 se quiser mais qualidade\n",
227
+ " learning_rate=2e-4,\n",
228
+ " fp16=not is_bfloat16_supported(),\n",
229
+ " bf16=is_bfloat16_supported(),\n",
230
+ " logging_steps=10,\n",
231
+ " optim='adamw_8bit',\n",
232
+ " weight_decay=0.01,\n",
233
+ " lr_scheduler_type='linear',\n",
234
+ " seed=42,\n",
235
+ " output_dir='ivrius_output',\n",
236
+ " report_to='none',\n",
237
+ " ),\n",
238
+ ")\n",
239
+ "\n",
240
+ "print('🚀 Iniciando treino...')\n",
241
+ "trainer_stats = trainer.train()\n",
242
+ "print(f'\\n✅ Treino concluído!')\n",
243
+ "print(f' Loss final: {trainer_stats.training_loss:.4f}')\n",
244
+ "print(f' Tempo: {trainer_stats.metrics[\"train_runtime\"]/60:.1f} minutos')"
245
+ ],
246
+ "execution_count": null,
247
+ "outputs": []
248
+ },
249
+ {
250
+ "cell_type": "code",
251
+ "metadata": {},
252
+ "source": [
253
+ "# ── Célula 8: Testar o modelo ─────────────────────────────────────\n",
254
+ "FastLanguageModel.for_inference(model)\n",
255
+ "\n",
256
+ "testes = [\n",
257
+ " 'O que é dano moral no direito brasileiro? Compare com o conceito americano.',\n",
258
+ " 'Explique o habeas corpus no Brasil e seu equivalente nos EUA.',\n",
259
+ " 'Qual a diferença entre prescrição e decadência no direito civil brasileiro?',\n",
260
+ "]\n",
261
+ "\n",
262
+ "for pergunta in testes:\n",
263
+ " prompt = ALPACA_PROMPT.format(instruction=pergunta, response='') \n",
264
+ " inputs = tokenizer([prompt], return_tensors='pt').to('cuda')\n",
265
+ " outputs = model.generate(**inputs, max_new_tokens=300,\n",
266
+ " temperature=0.3, do_sample=True,\n",
267
+ " pad_token_id=tokenizer.eos_token_id)\n",
268
+ " resposta = tokenizer.batch_decode(outputs)[0]\n",
269
+ " resposta_limpa = resposta.split('### Resposta:')[-1].replace(tokenizer.eos_token,'').strip()\n",
270
+ " print(f'\\n❓ {pergunta}')\n",
271
+ " print(f'💬 {resposta_limpa[:400]}')\n",
272
+ " print('─'*60)"
273
+ ],
274
+ "execution_count": null,
275
+ "outputs": []
276
+ },
277
+ {
278
+ "cell_type": "code",
279
+ "metadata": {},
280
+ "source": [
281
+ "# ── Célula 9: Salvar LoRA no HuggingFace ─────────────────────────\n",
282
+ "print(f'💾 Salvando LoRA em {HF_REPO_OUT}...')\n",
283
+ "model.save_pretrained('ivrius_lora')\n",
284
+ "tokenizer.save_pretrained('ivrius_lora')\n",
285
+ "\n",
286
+ "model.push_to_hub(HF_REPO_OUT, token=HF_TOKEN)\n",
287
+ "tokenizer.push_to_hub(HF_REPO_OUT, token=HF_TOKEN)\n",
288
+ "print(f'\\n✅ Modelo salvo em: https://huggingface.co/{HF_REPO_OUT}')"
289
+ ],
290
+ "execution_count": null,
291
+ "outputs": []
292
+ },
293
+ {
294
+ "cell_type": "code",
295
+ "metadata": {},
296
+ "source": [
297
+ "# ── Célula 10 (opcional): Merge + GGUF para LM Studio ────────────\n",
298
+ "# Descomente se quiser rodar localmente no LM Studio\n",
299
+ "\n",
300
+ "# print('🔧 Fazendo merge do modelo...')\n",
301
+ "# model.save_pretrained_merged('ivrius_merged', tokenizer, save_method='merged_16bit')\n",
302
+ "# model.push_to_hub_merged(HF_REPO_OUT + '-merged', tokenizer,\n",
303
+ "# save_method='merged_16bit', token=HF_TOKEN)\n",
304
+ "\n",
305
+ "# # Converter para GGUF (para LM Studio / Ollama)\n",
306
+ "# model.save_pretrained_gguf('ivrius_gguf', tokenizer, quantization_method='q4_k_m')\n",
307
+ "# model.push_to_hub_gguf(HF_REPO_OUT + '-gguf', tokenizer,\n",
308
+ "# quantization_method='q4_k_m', token=HF_TOKEN)\n",
309
+ "# print('✅ GGUF salvo!')\n",
310
+ "\n",
311
+ "print('Célula 10 pronta — descomente para gerar GGUF')"
312
+ ],
313
+ "execution_count": null,
314
+ "outputs": []
315
+ },
316
+ {
317
+ "cell_type": "markdown",
318
+ "metadata": {},
319
+ "source": [
320
+ "## ✅ Concluído!\n",
321
+ "\n",
322
+ "Seu modelo IVRIUS está treinado e salvo no HuggingFace.\n",
323
+ "\n",
324
+ "**Próximos passos:**\n",
325
+ "1. Descomentar célula 10 para gerar GGUF (LM Studio / Ollama)\n",
326
+ "2. Integrar no Lambda AWS via Bedrock Custom Model\n",
327
+ "3. Adicionar disclaimer OAB nas respostas\n",
328
+ "4. Integrar RAG com Qdrant + voyage-law-2\n",
329
+ "\n",
330
+ "**Modelo salvo em:** `MMR408/ivrius-llama-juridico-v1`\n",
331
+ "\n",
332
+ "---\n",
333
+ "_IVRIUS — Intelligent Virtual Research and Information System_ \n",
334
+ "_Dra. Miriam Mesquita — OAB_"
335
+ ]
336
+ }
337
+ ]
338
+ }