diff --git a/examples/configs/polygraph_eval_person_bio_ar.yaml b/examples/configs/polygraph_eval_person_bio_ar.yaml index 1158f928..764dca27 100644 --- a/examples/configs/polygraph_eval_person_bio_ar.yaml +++ b/examples/configs/polygraph_eval_person_bio_ar.yaml @@ -1,5 +1,3 @@ - - hydra: run: dir: ${cache_path}/${task}/${model.path}/${dataset}/${now:%Y-%m-%d}/${now:%H-%M-%S} @@ -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}' @@ -25,9 +18,13 @@ 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' @@ -35,23 +32,10 @@ generation_metrics: [{ 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 diff --git a/examples/configs/polygraph_eval_person_bio_en_jais.yaml b/examples/configs/polygraph_eval_person_bio_en_jais.yaml new file mode 100644 index 00000000..fe09bd3a --- /dev/null +++ b/examples/configs/polygraph_eval_person_bio_en_jais.yaml @@ -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 diff --git a/examples/configs/polygraph_eval_person_bio_en.yaml b/examples/configs/polygraph_eval_person_bio_en_mistral.yaml similarity index 91% rename from examples/configs/polygraph_eval_person_bio_en.yaml rename to examples/configs/polygraph_eval_person_bio_en_mistral.yaml index 57d779d6..0bab8614 100644 --- a/examples/configs/polygraph_eval_person_bio_en.yaml +++ b/examples/configs/polygraph_eval_person_bio_en_mistral.yaml @@ -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' diff --git a/examples/configs/polygraph_eval_person_bio_ru.yaml b/examples/configs/polygraph_eval_person_bio_ru.yaml index f01ecf80..5bb1d1e7 100644 --- a/examples/configs/polygraph_eval_person_bio_ru.yaml +++ b/examples/configs/polygraph_eval_person_bio_ru.yaml @@ -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'] @@ -21,9 +18,11 @@ 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' @@ -31,22 +30,8 @@ generation_metrics: [{ 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 diff --git a/examples/configs/polygraph_eval_person_bio_zh.yaml b/examples/configs/polygraph_eval_person_bio_zh.yaml index 3dda4c2b..ecc9fbf8 100644 --- a/examples/configs/polygraph_eval_person_bio_zh.yaml +++ b/examples/configs/polygraph_eval_person_bio_zh.yaml @@ -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 diff --git a/scripts/polygraph_eval b/scripts/polygraph_eval index b811e7fd..69abc28b 100755 --- a/scripts/polygraph_eval +++ b/scripts/polygraph_eval @@ -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 diff --git a/src/lm_polygraph/defaults/register_default_stat_calculators.py b/src/lm_polygraph/defaults/register_default_stat_calculators.py index afc3937c..e1bdd8d1 100644 --- a/src/lm_polygraph/defaults/register_default_stat_calculators.py +++ b/src/lm_polygraph/defaults/register_default_stat_calculators.py @@ -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. @@ -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) @@ -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, } @@ -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, } @@ -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, } @@ -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: diff --git a/src/lm_polygraph/defaults/stat_calculator_builders/default_ClaimsExtractor.py b/src/lm_polygraph/defaults/stat_calculator_builders/default_ClaimsExtractor.py index 5a4719f9..3889ce70 100644 --- a/src/lm_polygraph/defaults/stat_calculator_builders/default_ClaimsExtractor.py +++ b/src/lm_polygraph/defaults/stat_calculator_builders/default_ClaimsExtractor.py @@ -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) diff --git a/src/lm_polygraph/defaults/stat_calculator_builders/default_GreedyAlternativesFactPrefNLICalculator.py b/src/lm_polygraph/defaults/stat_calculator_builders/default_GreedyAlternativesFactPrefNLICalculator.py index 3ff70bc0..07eb2116 100644 --- a/src/lm_polygraph/defaults/stat_calculator_builders/default_GreedyAlternativesFactPrefNLICalculator.py +++ b/src/lm_polygraph/defaults/stat_calculator_builders/default_GreedyAlternativesFactPrefNLICalculator.py @@ -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) diff --git a/src/lm_polygraph/defaults/stat_calculator_builders/default_GreedyAlternativesNLICalculator.py b/src/lm_polygraph/defaults/stat_calculator_builders/default_GreedyAlternativesNLICalculator.py index 348fa337..c9b89762 100644 --- a/src/lm_polygraph/defaults/stat_calculator_builders/default_GreedyAlternativesNLICalculator.py +++ b/src/lm_polygraph/defaults/stat_calculator_builders/default_GreedyAlternativesNLICalculator.py @@ -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) diff --git a/src/lm_polygraph/defaults/stat_calculator_builders/default_SemanticMatrixCalculator.py b/src/lm_polygraph/defaults/stat_calculator_builders/default_SemanticMatrixCalculator.py index 6ae9ac02..ff8e1706 100644 --- a/src/lm_polygraph/defaults/stat_calculator_builders/default_SemanticMatrixCalculator.py +++ b/src/lm_polygraph/defaults/stat_calculator_builders/default_SemanticMatrixCalculator.py @@ -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) diff --git a/src/lm_polygraph/defaults/stat_calculator_builders/utils.py b/src/lm_polygraph/defaults/stat_calculator_builders/utils.py new file mode 100644 index 00000000..33da47d7 --- /dev/null +++ b/src/lm_polygraph/defaults/stat_calculator_builders/utils.py @@ -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 diff --git a/src/lm_polygraph/stat_calculators/extract_claims.py b/src/lm_polygraph/stat_calculators/extract_claims.py index 3d908d13..127d8d82 100644 --- a/src/lm_polygraph/stat_calculators/extract_claims.py +++ b/src/lm_polygraph/stat_calculators/extract_claims.py @@ -1,4 +1,5 @@ import re +import logging from typing import Dict, List, Optional, Tuple from dataclasses import dataclass @@ -11,6 +12,8 @@ from tqdm import tqdm from concurrent.futures import ThreadPoolExecutor +log = logging.getLogger("lm_polygraph") + @dataclass class Claim: @@ -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 diff --git a/src/lm_polygraph/stat_calculators/prompt.py b/src/lm_polygraph/stat_calculators/prompt.py index 2f9e3093..642ea785 100644 --- a/src/lm_polygraph/stat_calculators/prompt.py +++ b/src/lm_polygraph/stat_calculators/prompt.py @@ -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: @@ -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, @@ -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", ) diff --git a/src/lm_polygraph/utils/manager.py b/src/lm_polygraph/utils/manager.py index ecf3d359..f005adfd 100644 --- a/src/lm_polygraph/utils/manager.py +++ b/src/lm_polygraph/utils/manager.py @@ -141,18 +141,16 @@ def __init__( model (Model): Model to run benchmark on. Can be either lm_polygraph.WhiteboxModel or lm_polygraph.BlackboxModel estimators (List[Estimator]): List of estimators to evaluate at benchmark. + builder_env_stat_calc (BuilderEnvironmentStatCalculator): Environment seen by all stat calculators when + they are built in polygraph_eval script. + available_stat_calculators (List[StatCalculatorContainer]): List of stats calculators to use. + Can be initialized automatically with `register_default_stat_calculators`. generation_metrics (List[GenerationMetrics]): List of methods to use to calculate ground-truth uncertainty. ue_metrics (List[UEMetric]): List of methods to measure correlation between ground-truth uncertainties from `generation_metrics` and uncertainty estimators in `estimators`. processors (List[Processor]): List of processors to apply after each batch. - train_data (Optional[Dataset]): Dataset to train density-based estimators on. Can be set to None, if - no density-based method is used. Default: None. ignore_exceptions (bool): If true, exceptions on a new batch will be printed to stderr and the batch will be skipped. Useful to skip CUDA OOM errors on large datasets. Default: True. - deberta_batch_size (int): Batch size for DeBERTa model used in some estimators. Default: 10. - deberta_device (Optional[str]): The device to run deberta on. If None, will use 'cuda:0' if available, - 'cpu' otherwise. Default: None. - language (str): Language to test in claim-level benchmark, one of 'en', 'zh', 'ar', 'ru'. Default: 'en'. verbose (bool): If set, will print useful info during batch processing. Default: True. max_new_tokens (int): Maximum new tokens to use in generation. Default: 100. """