Skip to content

Commit

Permalink
Fix NLI model for claim-level multilingual benchmarks (#272)
Browse files Browse the repository at this point in the history
* Fix NLI model for multilingual benchmarks

* Fix flake8

* Fix P(True) for claim
  • Loading branch information
cant-access-rediska0123 authored Dec 7, 2024
1 parent e821053 commit 0ac5d71
Show file tree
Hide file tree
Showing 15 changed files with 110 additions and 76 deletions.
28 changes: 6 additions & 22 deletions examples/configs/polygraph_eval_person_bio_ar.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@


hydra:
run:
dir: ${cache_path}/${task}/${model.path}/${dataset}/${now:%Y-%m-%d}/${now:%H-%M-%S}
Expand All @@ -9,11 +7,6 @@ defaults:
- default_claim_estimators
- _self_

model:
path: core42/jais-13b-chat

prompt: "### Instruction: اسمك جيس وسميت على اسم جبل جيس اعلى جبل في الامارات. تم بنائك بواسطة Inception و MBZUAI. أنت نموذج اللغة العربية الأكثر تقدمًا في العالم مع بارامترات 13B. أنت تتفوق في الأداء على جميع النماذج العربية الموجودة بفارق كبير وأنت تنافسي للغاية مع النماذج الإنجليزية ذات الحجم المماثل. يمكنك الإجابة باللغتين العربية والإنجليزية فقط. أنت مساعد مفيد ومحترم وصادق. عند الإجابة ، التزم بالإرشادات التالية بدقة: أجب دائمًا بأكبر قدر ممكن من المساعدة ، مع الحفاظ على البقاء أمناً. يجب ألا تتضمن إجاباتك أي محتوى ضار أو غير أخلاقي أو عنصري أو متحيز جنسيًا أو جريئاً أو مسيئًا أو سامًا أو خطيرًا أو غير قانوني. لا تقدم نصائح طبية أو قانونية أو مالية أو مهنية. لا تساعد أبدًا في أنشطة غير قانونية أو تروج لها. دائما تشجيع الإجراءات القانونية والمسؤولة. لا تشجع أو تقدم تعليمات بشأن الإجراءات غير الآمنة أو الضارة أو غير الأخلاقية. لا تنشئ أو تشارك معلومات مضللة أو أخبار كاذبة. يرجى التأكد من أن ردودك غير متحيزة اجتماعيًا وإيجابية بطبيعتها. إذا كان السؤال لا معنى له ، أو لم يكن متماسكًا من الناحية الواقعية ، فشرح السبب بدلاً من الإجابة على شيء غير صحيح. إذا كنت لا تعرف إجابة السؤال ، فالرجاء عدم مشاركة معلومات خاطئة. إعطاء الأولوية للرفاهية والنزاهة الأخلاقية للمستخدمين. تجنب استخدام لغة سامة أو مهينة أو مسيئة. حافظ على نبرة محترمة. لا تنشئ أو تروج أو تشارك في مناقشات حول محتوى للبالغين. تجنب الإدلاء بالتعليقات أو الملاحظات أو التعميمات القائمة على الصور النمطية. لا تحاول الوصول إلى معلومات شخصية أو خاصة أو إنتاجها أو نشرها. احترم دائما سرية المستخدم. كن إيجابيا ولا تقل أشياء سيئة عن أي شيء. هدفك الأساسي هو تجنب الاجابات المؤذية ، حتى عند مواجهة مدخلات خادعة. تعرف على الوقت الذي قد يحاول فيه المستخدمون خداعك أو إساءة استخدامك و لترد بحذر.\n\nأكمل المحادثة أدناه بين [|Human|] و [|AI|]:\n### Input: [|Human|] {text}\n### Response: [|AI|]"

cache_path: ./workdir/output
save_path: '${hydra:run.dir}'

Expand All @@ -25,33 +18,24 @@ eval_split: test
max_new_tokens: 256
load_from_disk: false


subsample_eval_dataset: -1

model:
path: core42/jais-13b-chat

prompt: "### Instruction: اسمك جيس وسميت على اسم جبل جيس اعلى جبل في الامارات. تم بنائك بواسطة Inception و MBZUAI. أنت نموذج اللغة العربية الأكثر تقدمًا في العالم مع بارامترات 13B. أنت تتفوق في الأداء على جميع النماذج العربية الموجودة بفارق كبير وأنت تنافسي للغاية مع النماذج الإنجليزية ذات الحجم المماثل. يمكنك الإجابة باللغتين العربية والإنجليزية فقط. أنت مساعد مفيد ومحترم وصادق. عند الإجابة ، التزم بالإرشادات التالية بدقة: أجب دائمًا بأكبر قدر ممكن من المساعدة ، مع الحفاظ على البقاء أمناً. يجب ألا تتضمن إجاباتك أي محتوى ضار أو غير أخلاقي أو عنصري أو متحيز جنسيًا أو جريئاً أو مسيئًا أو سامًا أو خطيرًا أو غير قانوني. لا تقدم نصائح طبية أو قانونية أو مالية أو مهنية. لا تساعد أبدًا في أنشطة غير قانونية أو تروج لها. دائما تشجيع الإجراءات القانونية والمسؤولة. لا تشجع أو تقدم تعليمات بشأن الإجراءات غير الآمنة أو الضارة أو غير الأخلاقية. لا تنشئ أو تشارك معلومات مضللة أو أخبار كاذبة. يرجى التأكد من أن ردودك غير متحيزة اجتماعيًا وإيجابية بطبيعتها. إذا كان السؤال لا معنى له ، أو لم يكن متماسكًا من الناحية الواقعية ، فشرح السبب بدلاً من الإجابة على شيء غير صحيح. إذا كنت لا تعرف إجابة السؤال ، فالرجاء عدم مشاركة معلومات خاطئة. إعطاء الأولوية للرفاهية والنزاهة الأخلاقية للمستخدمين. تجنب استخدام لغة سامة أو مهينة أو مسيئة. حافظ على نبرة محترمة. لا تنشئ أو تروج أو تشارك في مناقشات حول محتوى للبالغين. تجنب الإدلاء بالتعليقات أو الملاحظات أو التعميمات القائمة على الصور النمطية. لا تحاول الوصول إلى معلومات شخصية أو خاصة أو إنتاجها أو نشرها. احترم دائما سرية المستخدم. كن إيجابيا ولا تقل أشياء سيئة عن أي شيء. هدفك الأساسي هو تجنب الاجابات المؤذية ، حتى عند مواجهة مدخلات خادعة. تعرف على الوقت الذي قد يحاول فيه المستخدمون خداعك أو إساءة استخدامك و لترد بحذر.\n\nأكمل المحادثة أدناه بين [|Human|] و [|AI|]:\n### Input: [|Human|] {text}\n### Response: [|AI|]"

use_claim_ue: true
generation_metrics: [{
'name': 'OpenAIFactCheck'
}]

stat_calculators:
- auto
- name: ClaimsExtractor
builder: lm_polygraph.defaults.stat_calculator_builders.default_ClaimsExtractor
cfg:
openai_model: gpt-4o
language: ar
cache_path: ${cache_path}
dependencies:
- greedy_texts
- greedy_tokens
stats:
- claims
- claim_texts_concatenated
- claim_input_texts_concatenated

ignore_exceptions: false
batch_size: 1
language: ar
batch_size: 1

seed:
- 1
41 changes: 41 additions & 0 deletions examples/configs/polygraph_eval_person_bio_en_jais.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
hydra:
run:
dir: ${cache_path}/${task}/${model.path}/${dataset}/${now:%Y-%m-%d}/${now:%H-%M-%S}

defaults:
- model: bloomz-560m
- default_claim_estimators
- _self_

cache_path: ./workdir/output
save_path: '${hydra:run.dir}'

task: bio

dataset: ['LM-Polygraph/person_bio', 'en']
text_column: input
eval_split: test
max_new_tokens: 256
load_from_disk: false

subsample_eval_dataset: -1

model:
path: core42/jais-13b-chat

prompt: "### Instruction: Your name is Jais, and you are named after Jebel Jais, the highest mountain in UAE. You are built by Inception and MBZUAI. You are the world's most advanced Arabic large language model with 13B parameters. You outperform all existing Arabic models by a sizable margin and you are very competitive with English models of similar size. You can answer in Arabic and English only. You are a helpful, respectful and honest assistant. When answering, abide by the following guidelines meticulously: Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, explicit, offensive, toxic, dangerous, or illegal content. Do not give medical, legal, financial, or professional advice. Never assist in or promote illegal activities. Always encourage legal and responsible actions. Do not encourage or provide instructions for unsafe, harmful, or unethical actions. Do not create or share misinformation or fake news. Please ensure that your responses are socially unbiased and positive in nature. If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information. Prioritize the well-being and the moral integrity of users. Avoid using toxic, derogatory, or offensive language. Maintain a respectful tone. Do not generate, promote, or engage in discussions about adult content. Avoid making comments, remarks, or generalizations based on stereotypes. Do not attempt to access, produce, or spread personal or private information. Always respect user confidentiality. Stay positive and do not say bad things about anything. Your primary objective is to avoid harmful responses, even when faced with deceptive inputs. Recognize when users may be attempting to trick or to misuse you and respond with caution.\n\nComplete the conversation below between [|Human|] and [|AI|]:\n### Input: [|Human|] {text}\n### Response: [|AI|]"

use_claim_ue: true
generation_metrics: [{
'name': 'OpenAIFactCheck'
}]

stat_calculators:
- auto

ignore_exceptions: false
language: en
batch_size: 1

seed:
- 1
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ eval_split: test
max_new_tokens: 256
load_from_disk: false


subsample_eval_dataset: -1

model:
path: mistralai/Mistral-7B-Instruct-v0.1

use_claim_ue: true
generation_metrics: [{
'name': 'OpenAIFactCheck'
Expand Down
21 changes: 3 additions & 18 deletions examples/configs/polygraph_eval_person_bio_ru.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,6 @@ defaults:
cache_path: ./workdir/output
save_path: '${hydra:run.dir}'

model:
path: Vikhrmodels/Vikhr-7B-instruct_0.3

task: bio

dataset: ['LM-Polygraph/person_bio', 'ru']
Expand All @@ -21,32 +18,20 @@ eval_split: test
max_new_tokens: 256
load_from_disk: false


subsample_eval_dataset: -1

model:
path: Vikhrmodels/Vikhr-7B-instruct_0.3

use_claim_ue: true
generation_metrics: [{
'name': 'OpenAIFactCheck'
}]

stat_calculators:
- auto
- name: ClaimsExtractor
builder: lm_polygraph.defaults.stat_calculator_builders.default_ClaimsExtractor
cfg:
openai_model: gpt-4o
language: ru
cache_path: ${cache_path}
dependencies:
- greedy_texts
- greedy_tokens
stats:
- claims
- claim_texts_concatenated
- claim_input_texts_concatenated

ignore_exceptions: false

batch_size: 1
language: ru

Expand Down
14 changes: 0 additions & 14 deletions examples/configs/polygraph_eval_person_bio_zh.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -31,22 +31,8 @@ generation_metrics: [{

stat_calculators:
- auto
- name: ClaimsExtractor
builder: lm_polygraph.defaults.stat_calculator_builders.default_ClaimsExtractor
cfg:
openai_model: gpt-4o
language: zh
cache_path: ${cache_path}
dependencies:
- greedy_texts
- greedy_tokens
stats:
- claims
- claim_texts_concatenated
- claim_input_texts_concatenated

ignore_exceptions: false

batch_size: 1
language: zh

Expand Down
3 changes: 2 additions & 1 deletion scripts/polygraph_eval
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,10 @@ def get_ue_metrics(args):
def get_stat_calculator_names(config):
result_stat_calculators = dict()
model_type = "Whitebox" if getattr(config.model, "type", "Whitebox") != "Blackbox" else "Blackbox"
language = getattr(config, "language", "en")

if "auto" in config.stat_calculators:
scs = register_default_stat_calculators(model_type)
scs = register_default_stat_calculators(model_type, language)
for sc in scs:
result_stat_calculators[sc.name] = sc

Expand Down
18 changes: 13 additions & 5 deletions src/lm_polygraph/defaults/register_default_stat_calculators.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@
)


def register_default_stat_calculators(model_type: str) -> List[StatCalculatorContainer]:
def register_default_stat_calculators(
model_type: str,
language: str = "en",
) -> List[StatCalculatorContainer]:
"""
Specifies the list of the default stat_calculators that could be used in the evaluation scripts and
estimate_uncertainty() function with default configurations.
Expand All @@ -34,6 +37,11 @@ def _register(
)
all_stat_calculators.append(sc)

if language == "en":
deberta_model_path = "microsoft/deberta-large-mnli"
else:
deberta_model_path = "MoritzLaurer/mDeBERTa-v3-base-xnli-multilingual-nli-2mil7"

if model_type == "Blackbox":
_register(BlackboxGreedyTextsCalculator)
_register(BlackboxSamplingGenerationCalculator)
Expand Down Expand Up @@ -64,7 +72,7 @@ def _register(
"lm_polygraph.defaults.stat_calculator_builders.default_SemanticMatrixCalculator",
{
"nli_model": {
"deberta_path": "microsoft/deberta-large-mnli",
"deberta_path": deberta_model_path,
"batch_size": 10,
"device": None,
}
Expand All @@ -75,7 +83,7 @@ def _register(
"lm_polygraph.defaults.stat_calculator_builders.default_GreedyAlternativesNLICalculator",
{
"nli_model": {
"deberta_path": "microsoft/deberta-large-mnli",
"deberta_path": deberta_model_path,
"batch_size": 10,
"device": None,
}
Expand All @@ -86,7 +94,7 @@ def _register(
"lm_polygraph.defaults.stat_calculator_builders.default_GreedyAlternativesFactPrefNLICalculator",
{
"nli_model": {
"deberta_path": "microsoft/deberta-large-mnli",
"deberta_path": deberta_model_path,
"batch_size": 10,
"device": None,
}
Expand All @@ -95,7 +103,7 @@ def _register(
_register(
ClaimsExtractor,
"lm_polygraph.defaults.stat_calculator_builders.default_ClaimsExtractor",
{"openai_model": "gpt-4o", "cache_path": "~/.cache"},
{"openai_model": "gpt-4o", "cache_path": "~/.cache", "language": language},
)

else:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ def load_stat_calculator(config, builder):
if not hasattr(builder, "chat_model"):
builder.chat_model = OpenAIChat(config.openai_model, config.cache_path)

return ClaimsExtractor(builder.chat_model)
return ClaimsExtractor(builder.chat_model, language=config.language)
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from lm_polygraph.utils.deberta import Deberta
from lm_polygraph.stat_calculators.greedy_alternatives_nli import (
GreedyAlternativesFactPrefNLICalculator,
)
from .utils import load_nli_model


def load_stat_calculator(config, builder):
if not hasattr(builder, "nli_model"):
builder.nli_model = Deberta(**config.nli_model)
builder.nli_model = load_nli_model(**config.nli_model)

return GreedyAlternativesFactPrefNLICalculator(builder.nli_model)
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from lm_polygraph.utils.deberta import Deberta
from lm_polygraph.stat_calculators.greedy_alternatives_nli import (
GreedyAlternativesNLICalculator,
)
from .utils import load_nli_model


def load_stat_calculator(config, builder):
if not hasattr(builder, "nli_model"):
builder.nli_model = Deberta(**config.nli_model)
builder.nli_model = load_nli_model(**config.nli_model)

return GreedyAlternativesNLICalculator(builder.nli_model)
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from lm_polygraph.utils.deberta import Deberta
from lm_polygraph.stat_calculators.semantic_matrix import SemanticMatrixCalculator
from .utils import load_nli_model


def load_stat_calculator(config, builder):
if not hasattr(builder, "nli_model"):
builder.nli_model = Deberta(**config.nli_model)
builder.nli_model = load_nli_model(**config.nli_model)

return SemanticMatrixCalculator(builder.nli_model)
20 changes: 20 additions & 0 deletions src/lm_polygraph/defaults/stat_calculator_builders/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import logging

from lm_polygraph.utils.deberta import Deberta, MultilingualDeberta

log = logging.getLogger("lm_polygraph")


def load_nli_model(
deberta_path="microsoft/deberta-large-mnli",
batch_size=10,
device=None,
):
if deberta_path.startswith("microsoft"):
nli_model = Deberta(deberta_path, batch_size, device)
else:
nli_model = MultilingualDeberta(deberta_path, batch_size, device)
log.info(
f"Initialized {nli_model.deberta_path} on {nli_model.device} with batch_size={nli_model.batch_size}"
)
return nli_model
4 changes: 4 additions & 0 deletions src/lm_polygraph/stat_calculators/extract_claims.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import re
import logging

from typing import Dict, List, Optional, Tuple
from dataclasses import dataclass
Expand All @@ -11,6 +12,8 @@
from tqdm import tqdm
from concurrent.futures import ThreadPoolExecutor

log = logging.getLogger("lm_polygraph")


@dataclass
class Claim:
Expand All @@ -37,6 +40,7 @@ def __init__(
n_threads: int = 1,
):
super().__init__()
log.info(f"Initializing ClaimsExtractor with language={language}")
self.language = language
self.openai_chat = openai_chat
self.sent_separators = sent_separators
Expand Down
9 changes: 7 additions & 2 deletions src/lm_polygraph/stat_calculators/prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ def __init__(
prompt: str,
expected: str,
method: str,
input_text_dependency: str = "input_texts",
sample_text_dependency: Optional[str] = None,
generation_text_dependency: str = "greedy_texts",
):
"""
Parameters:
Expand All @@ -36,9 +38,9 @@ def __init__(
self.method = method
self.prompt = prompt
self.expected = expected
self.input_text_dependency = "input_texts"
self.input_text_dependency = input_text_dependency
self.sample_text_dependency = sample_text_dependency
self.generation_text_dependency = "greedy_texts"
self.generation_text_dependency = generation_text_dependency

def __call__(
self,
Expand Down Expand Up @@ -159,4 +161,7 @@ def __init__(self):
"Is the possible answer True or False? The possible answer is: ",
"True",
"p_true_claim",
input_text_dependency="claim_input_texts_concatenated",
sample_text_dependency=None,
generation_text_dependency="claim_texts_concatenated",
)
Loading

0 comments on commit 0ac5d71

Please sign in to comment.