/ Модель

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

Контекст
8 192 токена
Параметры
7,5 млрд
Размер весов
16,1 ГБ
Лицензия
Llama 3
Архитектура
llama · dense
Базовая модель
llama-3-8b
Библиотека
transformers
Опубликована
20 авг 2024

Llama-3-Legal-8B

Генерация текстаТекст → текст4 профессии
503скачиваний за 30 дней3лайкавеса обновлены20 ноя 2026

Описание модели

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

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

Llama-3-Legal-8B — специализированная текстовая модель CSroseX для поиска и точного извлечения предложений о положениях коммерческих договоров. Она принимает тип нужного положения и фрагмент договора, затем цитирует относящийся к нему текст или отвечает «Not found.». Модель охватывает 41 тип положений из CUAD и предназначена для юристов, помощников юристов и разработчиков юридических сервисов, которым нужно быстро находить нужные условия в договорах.

Модель основана на Llama 3 с архитектурой LlamaForCausalLM и примерно 7,5 млрд параметров; она дообучена методом QLoRA на примерах CUAD. Контекст составляет до 8192 токенов, однако при работе с целым договором карточка рекомендует разбивать его на перекрывающиеся страницы примерно по 500 токенов. Доступны веса safetensors и варианты GGUF Q4_K_M и Q8_0. Модель рассчитана на английские договоры и показывает заметно различающиеся результаты по типам положений.

Это инструмент поиска и извлечения текста, а не система юридических консультаций, оценки качества условий или общего юридического чата. Результаты нужно сверять с оригиналом: модель слабее работает, например, с названиями сторон и сложными условиями об изменении контроля, а при обработке целого договора может выдавать лишние совпадения. Лицензия — llama3.

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

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

Ограничения

Качество неодинаково для разных типов положений: модель хуже справляется с определением сторон и сложными условиями об изменении контроля; при разбиении полного договора может возвращать лишние кандидаты. Она обучена на англоязычных коммерческих договорах США из CUAD, не даёт юридических рекомендаций, а её ответы следует сверять с оригиналом.

Публичные бенчмарки

Результаты из открытых лидербордов в сравнении с лидерами каталога

Публичных оценок пока нет

В подключённых источниках результатов этой модели не нашлось. Отсутствие оценки не значит, что модель хуже: её могли просто не проверять.

Источники: Hugging Face Leaderboards, Hugging Face Eval Results, Open LLM v2, MTEB, timm, Open ASR, EvalPlus, LLM Stats

Бенчмарки пользователейпока нет

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

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

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

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

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

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

    Модели ответят на каждую задачу, судья оценит ответы по шкале 0–100.

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

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

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

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

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

Открыть на Hugging Face

Llama-3-Legal-8B

⚖️ Llama-3-Legal-8B

Finds and quotes clauses in commercial contracts, or tells you plainly that they aren't there.

Built with Meta Llama 3 License: Llama 3 Dataset: CUAD GGUF

0.73599.6%95.8%
word overlap with the correct clause(previous version: 0.185)of answers are real text from the contract(previous version: 12.3%)correct "Not found." when the clause is absent(previous version: 0%)

Measured on 1,000 pages from 102 contracts the model never saw during training.

🔁 Downloaded before 20 November 2026? That copy is the old version. Python code that loads this repo updates automatically. GGUF files must be downloaded again. The old version remains in this repo's history.


What it does

Give the model a clause type and a piece of a contract. It returns the exact sentences from the contract about that clause, or Not found..

Question: Highlight the parts (if any) of this contract related to "Governing Law" that should be reviewed by a lawyer.

Contract excerpt: …This Agreement shall be interpreted in accordance with the laws of the State of Indiana. Neither party may assign…

Model: This Agreement shall be interpreted in accordance with the laws of the State of Indiana.

Who it's for: lawyers, paralegals, and legal-tech developers who need to locate specific clauses in long contracts quickly, the way a highlighter would.

Not for: legal advice, judging whether a clause is good or bad, or general legal chat. It points to the text; a person makes the call.

It recognises the 41 clause types of the CUAD dataset:

Document Name · Parties · Agreement Date · Effective Date · Expiration Date · Renewal Term · Notice Period To Terminate Renewal · Governing Law · Most Favored Nation · Non-Compete · Exclusivity · No-Solicit Of Customers · Competitive Restriction Exception · No-Solicit Of Employees · Non-Disparagement · Termination For Convenience · Rofr/Rofo/Rofn · Change Of Control · Anti-Assignment · Revenue/Profit Sharing · Price Restrictions · Minimum Commitment · Volume Restriction · Ip Ownership Assignment · Joint Ip Ownership · License Grant · Non-Transferable License · Affiliate License-Licensor · Affiliate License-Licensee · Unlimited/All-You-Can-Eat-License · Irrevocable Or Perpetual License · Source Code Escrow · Post-Termination Services · Audit Rights · Uncapped Liability · Cap On Liability · Liquidated Damages · Warranty Duration · Insurance · Covenant Not To Sue · Third Party Beneficiary


Quick start

1. One page of a contract

Write the message as the question, then a line containing only ---, then the contract text. The prompt format is stored in the tokenizer, so apply_chat_template builds the correct prompt for you.

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

repo = "CSroseX/Llama-3-Legal-8B"
tok = AutoTokenizer.from_pretrained(repo)
model = AutoModelForCausalLM.from_pretrained(repo, dtype=torch.float16, device_map="auto")

question = 'Highlight the parts (if any) of this contract related to "Governing Law" that should be reviewed by a lawyer.'
excerpt = "...paste up to about one page (~500 tokens) of the contract here..."

messages = [{"role": "user", "content": f"{question}\n---\n{excerpt}"}]
inputs = tok.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True).to(model.device)
output = model.generate(**inputs, max_new_tokens=256)
print(tok.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True))

💡 Small GPU? Load in 4-bit (about 6 GB of VRAM) by adding quantization_config=BitsAndBytesConfig(load_in_4bit=True) to from_pretrained.

2. A whole contract

The model was trained on pages of about 500 tokens. For a full contract, split it into overlapping pages, ask each page, and merge the answers:

def find_clause(contract, question, window=512, overlap=64):
    offsets = tok(contract, add_special_tokens=False, return_offsets_mapping=True)["offset_mapping"]
    n = len(offsets)
    starts = [s for s in range(0, n, window - overlap) if s == 0 or s < n - overlap]
    found = []
    for s in starts:
        page = contract[offsets[s][0] : offsets[min(s + window, n) - 1][1]]
        messages = [{"role": "user", "content": f"{question}\n---\n{page}"}]
        inputs = tok.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True).to(model.device)
        output = model.generate(**inputs, max_new_tokens=256)
        answer = tok.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True).strip()
        if not answer.lower().startswith("not found"):
            found += [line.strip() for line in answer.split("\n") if line.strip()]
    unique = list(dict.fromkeys(found))
    return [a for a in unique if not any(a != b and a in b for b in unique)] or ["Not found."]

print(find_clause(open("contract.txt").read(), question))

The last line removes duplicates. When a clause sits where two pages overlap, the model quotes it from both pages, and only the complete version is kept.

Run locally (GGUF)

FileSizeUse when
unsloth.Q8_0.gguf8.5 GBBest quality, needs ~10 GB RAM
unsloth.Q4_K_M.gguf4.9 GBOrdinary laptops, slightly lower quality

Both files contain the prompt format, for apps such as LM Studio and llama.cpp. If your app does not apply it, send this exact prompt yourself:

Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.

### Instruction:
{question}
Quote the exact text from the contract excerpt that answers this, one passage per line. If there is none, answer "Not found."

### Input:
{contract excerpt}

### Response:

How well it works

All three models took the same exam: 500 pages that contain the answer and 500 that don't, cut from CUAD's 102 test contracts. None of these contracts were used in training. A program does the marking.

ScoreBase Llama 3 8BPrevious versionLlama-3-Legal-8B
Word overlap with the correct clause ↑0.0030.1850.735
Answers found (≥ half the words right) ↑0.2%14.6%73.8%
Missed: said "Not found." but the answer was there ↓86.8%0.0%8.2%
Correct "Not found." when nothing was there ↑83.6%0.0%95.8%
Answer is not real text from the contract ↓93.2%87.7%0.4%

By clause type (word overlap, new model; clause types with at least 10 test pages):

Clause typeScore
Renewal Term0.97✅ Strong
Governing Law0.97✅ Strong
Expiration Date0.96✅ Strong
Document Name0.95✅ Strong
Agreement Date0.93✅ Strong
Effective Date0.91✅ Strong
Anti-Assignment0.86✅ Strong
Change Of Control0.28⚠️ Weak
Parties0.25⚠️ Weak

Whole-contract test: 3 complete test contracts × 6 clause types, run through the page-splitting code above. Average score 0.77.

Full results: evaluation details on GitHub


How it was trained

Base modelLlama 3 8B (unsloth/llama-3-8b-bnb-4bit for training, merged into unsloth/llama-3-8b in float16)
MethodQLoRA with Unsloth: rank 16, alpha 16, all attention and MLP projections
DataCUAD: 13,705 examples from 388 contracts. 20 contracts held out for validation, 102 for testing.
Examples512-token contract pages (up to 1,024 for long clauses). The clause sits at a random position. 21.7% are "Not found." pages.
LossOnly the answer is graded; the question and contract text are masked
Schedule1 epoch, 1,713 steps, effective batch 8, learning rate 2e-4 with linear decay
Hardware1 × NVIDIA T4 (Kaggle free tier), 7.7 hours
Validation loss0.723 → 0.076

Every step is reproducible from the notebooks in github.com/CSroseX/Legal-Llama: diagnosis, feasibility, training, evaluation and publishing.


License and credits

@article{hendrycks2021cuad,
  title   = {CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review},
  author  = {Hendrycks, Dan and Burns, Collin and Chen, Anya and Ball, Spencer},
  journal = {NeurIPS},
  year    = {2021}
}

What changed from the previous version

The first version of this model (2024) rambled and invented answers. It has been rebuilt from scratch.

BeforeNow
AnswersReworded or invented. 87.7% weren't text from the contract.Quoted word for word. 99.6% are real contract text.
Absent clausesNever said "Not found." and always made something upSays "Not found." correctly 95.8% of the time
Accuracy (word overlap)0.1850.735
Prompt formatNot saved, so apps sent the wrong format and the model rambledSaved in the tokenizer and in both GGUF files
Training dataWhole contracts, mostly longer than the model could read, so answers were often cut offOne page per example, containing the answer or teaching "Not found."
Name and licenseCalled "Llama 3.1" (it's Llama 3) and labelled Apache-2.0Correct name and the Llama 3 Community License
FilesOld weights stored twice (.bin + .safetensors, 40.7 GB)One set of weights plus Q8_0 and Q4_K_M GGUF
EvidenceNoneMeasured on unseen contracts, with reproducible notebooks

Limitations

  • Uneven across clause types. It's strongest on dates, governing law, renewal and assignment (0.86–0.97). It's weak on Parties (0.25: it finds the main company names but misses the nicknames each contract uses) and on long, complex clauses such as Change of Control (0.28). Because it reads one page at a time, it can also return extra candidates on full contracts, such as a signature date alongside the agreement date.
  • A review aid, not legal advice. It was trained only on CUAD's 510 English-language US commercial contracts. Always check its output against the contract.

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

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

GPU в ailist

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

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

Подбираем GPU…

Класс архитектуры
LlamaForCausalLM
Ревизия весов
6cc9984

0 моделей