crfm-helm 0.5.3__py3-none-any.whl → 0.5.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of crfm-helm might be problematic. Click here for more details.

Files changed (606) hide show
  1. crfm_helm-0.5.5.dist-info/METADATA +413 -0
  2. crfm_helm-0.5.5.dist-info/RECORD +894 -0
  3. {crfm_helm-0.5.3.dist-info → crfm_helm-0.5.5.dist-info}/WHEEL +1 -1
  4. helm/benchmark/adaptation/adapter_spec.py +13 -1
  5. helm/benchmark/adaptation/adapters/adapter_factory.py +15 -1
  6. helm/benchmark/adaptation/adapters/binary_ranking_adapter.py +1 -1
  7. helm/benchmark/adaptation/adapters/chat_adapter.py +49 -0
  8. helm/benchmark/adaptation/adapters/ehr_instruction_adapter.py +108 -0
  9. helm/benchmark/adaptation/adapters/generation_adapter.py +1 -1
  10. helm/benchmark/adaptation/adapters/in_context_learning_adapter.py +1 -1
  11. helm/benchmark/adaptation/adapters/language_modeling_adapter.py +1 -1
  12. helm/benchmark/adaptation/adapters/multimodal/generation_multimodal_adapter.py +4 -2
  13. helm/benchmark/adaptation/adapters/multimodal/in_context_learning_multimodal_adapter.py +1 -1
  14. helm/benchmark/adaptation/adapters/multimodal/multiple_choice_joint_multimodal_adapter.py +1 -1
  15. helm/benchmark/adaptation/adapters/multimodal/test_in_context_learning_multimodal_adapter.py +4 -2
  16. helm/benchmark/adaptation/adapters/multimodal/test_multimodal_prompt.py +1 -1
  17. helm/benchmark/adaptation/adapters/multiple_choice_calibrated_adapter.py +1 -1
  18. helm/benchmark/adaptation/adapters/multiple_choice_joint_adapter.py +2 -2
  19. helm/benchmark/adaptation/adapters/multiple_choice_joint_chain_of_thought_adapter.py +87 -0
  20. helm/benchmark/adaptation/adapters/multiple_choice_separate_adapter.py +1 -1
  21. helm/benchmark/adaptation/adapters/test_generation_adapter.py +3 -3
  22. helm/benchmark/adaptation/adapters/test_language_modeling_adapter.py +2 -2
  23. helm/benchmark/adaptation/adapters/test_multiple_choice_joint_adapter.py +2 -2
  24. helm/benchmark/adaptation/common_adapter_specs.py +69 -4
  25. helm/benchmark/adaptation/prompt.py +1 -1
  26. helm/benchmark/annotation/aci_bench_annotator.py +95 -0
  27. helm/benchmark/annotation/air_bench_annotator.py +20 -5
  28. helm/benchmark/annotation/annotator.py +5 -0
  29. helm/benchmark/annotation/annotator_factory.py +3 -20
  30. helm/benchmark/annotation/anthropic_red_team_annotator.py +11 -24
  31. helm/benchmark/annotation/autobencher_capabilities_annotator.py +107 -0
  32. helm/benchmark/annotation/autobencher_safety_annotator.py +98 -0
  33. helm/benchmark/annotation/bigcodebench_annotator.py +108 -0
  34. helm/benchmark/annotation/bird_sql_annotator.py +58 -0
  35. helm/benchmark/annotation/call_center_annotator.py +22 -11
  36. helm/benchmark/annotation/chw_care_plan_annotator.py +98 -0
  37. helm/benchmark/annotation/czech_bank_qa_annotator.py +78 -0
  38. helm/benchmark/annotation/dischargeme_annotator.py +107 -0
  39. helm/benchmark/annotation/ehr_sql_annotator.py +87 -0
  40. helm/benchmark/annotation/harm_bench_annotator.py +11 -24
  41. helm/benchmark/annotation/helpdesk_call_summarization_annotator.py +131 -0
  42. helm/benchmark/annotation/image2struct/image_compiler_annotator.py +6 -1
  43. helm/benchmark/annotation/live_qa_annotator.py +10 -5
  44. helm/benchmark/annotation/med_dialog_annotator.py +99 -0
  45. helm/benchmark/annotation/medalign_annotator.py +100 -0
  46. helm/benchmark/annotation/medi_qa_annotator.py +98 -0
  47. helm/benchmark/annotation/medication_qa_annotator.py +90 -61
  48. helm/benchmark/annotation/mental_health_annotator.py +98 -0
  49. helm/benchmark/annotation/mimic_rrs_annotator.py +100 -0
  50. helm/benchmark/annotation/model_as_judge.py +281 -18
  51. helm/benchmark/annotation/mtsamples_procedures_annotator.py +98 -0
  52. helm/benchmark/annotation/mtsamples_replicate_annotator.py +101 -0
  53. helm/benchmark/annotation/omni_math/gpt_evaluation_template.txt +152 -0
  54. helm/benchmark/annotation/omni_math/gpt_evaluation_zero_shot_template.txt +36 -0
  55. helm/benchmark/annotation/omni_math_annotator.py +132 -0
  56. helm/benchmark/annotation/simple_safety_tests_annotator.py +11 -25
  57. helm/benchmark/annotation/spider_annotator.py +18 -0
  58. helm/benchmark/annotation/starr_patient_instructions_annotator.py +98 -0
  59. helm/benchmark/annotation/wildbench/eval_template.pairwise.v2.md +75 -0
  60. helm/benchmark/annotation/wildbench/eval_template.score.v2.md +66 -0
  61. helm/benchmark/annotation/wildbench_annotator.py +119 -0
  62. helm/benchmark/annotation/xstest_annotator.py +20 -30
  63. helm/benchmark/annotation_executor.py +35 -15
  64. helm/benchmark/augmentations/cleva_perturbation.py +9 -8
  65. helm/benchmark/augmentations/contraction_expansion_perturbation.py +2 -2
  66. helm/benchmark/augmentations/contrast_sets_perturbation.py +2 -2
  67. helm/benchmark/augmentations/dialect_perturbation.py +4 -5
  68. helm/benchmark/augmentations/extra_space_perturbation.py +2 -2
  69. helm/benchmark/augmentations/filler_words_perturbation.py +2 -2
  70. helm/benchmark/augmentations/gender_perturbation.py +2 -2
  71. helm/benchmark/augmentations/lowercase_perturbation.py +2 -2
  72. helm/benchmark/augmentations/mild_mix_perturbation.py +6 -6
  73. helm/benchmark/augmentations/misspelling_perturbation.py +2 -2
  74. helm/benchmark/augmentations/person_name_perturbation.py +4 -5
  75. helm/benchmark/augmentations/perturbation.py +1 -1
  76. helm/benchmark/augmentations/space_perturbation.py +2 -2
  77. helm/benchmark/augmentations/suffix_perturbation.py +2 -2
  78. helm/benchmark/augmentations/synonym_perturbation.py +4 -3
  79. helm/benchmark/augmentations/test_perturbation.py +16 -13
  80. helm/benchmark/augmentations/translate_perturbation.py +2 -2
  81. helm/benchmark/augmentations/typos_perturbation.py +2 -2
  82. helm/benchmark/data_preprocessor.py +2 -2
  83. helm/benchmark/huggingface_registration.py +2 -7
  84. helm/benchmark/metrics/aci_bench_metrics.py +34 -0
  85. helm/benchmark/metrics/basic_metrics.py +6 -6
  86. helm/benchmark/metrics/bbq_metrics.py +2 -2
  87. helm/benchmark/metrics/bias_metrics.py +12 -3
  88. helm/benchmark/metrics/bigcodebench_metrics.py +25 -0
  89. helm/benchmark/metrics/bird_sql_metrics.py +28 -0
  90. helm/benchmark/metrics/chw_care_plan_metrics.py +34 -0
  91. helm/benchmark/metrics/classification_metrics.py +76 -12
  92. helm/benchmark/metrics/cleva_harms_metrics.py +8 -7
  93. helm/benchmark/metrics/code_metrics.py +5 -5
  94. helm/benchmark/metrics/comet_metric.py +125 -0
  95. helm/benchmark/metrics/common_metric_specs.py +9 -2
  96. helm/benchmark/metrics/conv_fin_qa_calc_metrics.py +72 -0
  97. helm/benchmark/metrics/copyright_metrics.py +4 -4
  98. helm/benchmark/metrics/czech_bank_qa_metrics.py +29 -0
  99. helm/benchmark/metrics/decodingtrust_fairness_metrics.py +2 -2
  100. helm/benchmark/metrics/decodingtrust_privacy_metrics.py +2 -2
  101. helm/benchmark/metrics/decodingtrust_stereotype_bias_metrics.py +2 -2
  102. helm/benchmark/metrics/dischargeme_metrics.py +34 -0
  103. helm/benchmark/metrics/disinformation_metrics.py +4 -4
  104. helm/benchmark/metrics/dry_run_metrics.py +5 -5
  105. helm/benchmark/metrics/efficiency_metrics.py +3 -3
  106. helm/benchmark/metrics/ehr_sql_metrics.py +103 -0
  107. helm/benchmark/metrics/evaluate_instances_metric.py +3 -3
  108. helm/benchmark/metrics/evaluate_reference_metrics.py +144 -16
  109. helm/benchmark/metrics/gpqa_chain_of_thought_metric.py +103 -0
  110. helm/benchmark/metrics/gpt4_audio_critique_metrics.py +167 -0
  111. helm/benchmark/metrics/helpdesk_call_summarization_metrics.py +36 -0
  112. helm/benchmark/metrics/ifeval/instructions.py +1574 -0
  113. helm/benchmark/metrics/ifeval/instructions_registry.py +182 -0
  114. helm/benchmark/metrics/ifeval/instructions_registry.pyi +3 -0
  115. helm/benchmark/metrics/ifeval/instructions_util.py +153 -0
  116. helm/benchmark/metrics/ifeval_metrics.py +55 -0
  117. helm/benchmark/metrics/image_generation/aesthetics_metrics.py +1 -1
  118. helm/benchmark/metrics/image_generation/detection_metrics.py +1 -1
  119. helm/benchmark/metrics/image_generation/detectors/vitdet.py +1 -1
  120. helm/benchmark/metrics/image_generation/fractal_dimension/test_fractal_dimension_util.py +1 -1
  121. helm/benchmark/metrics/image_generation/fractal_dimension_metric.py +1 -1
  122. helm/benchmark/metrics/image_generation/nsfw_metrics.py +1 -1
  123. helm/benchmark/metrics/image_generation/q16/test_q16.py +3 -1
  124. helm/benchmark/metrics/image_generation/q16_toxicity_metrics.py +1 -1
  125. helm/benchmark/metrics/image_generation/skin_tone_metrics.py +2 -2
  126. helm/benchmark/metrics/image_generation/watermark/test_watermark_detector.py +1 -1
  127. helm/benchmark/metrics/image_generation/watermark_metrics.py +1 -1
  128. helm/benchmark/metrics/instruction_following_critique_metrics.py +4 -4
  129. helm/benchmark/metrics/language_modeling_metrics.py +4 -4
  130. helm/benchmark/metrics/machine_translation_metrics.py +2 -2
  131. helm/benchmark/metrics/med_dialog_metrics.py +34 -0
  132. helm/benchmark/metrics/medalign_metrics.py +34 -0
  133. helm/benchmark/metrics/medcalc_bench_metrics.py +124 -0
  134. helm/benchmark/metrics/medec_metrics.py +101 -0
  135. helm/benchmark/metrics/medi_qa_metrics.py +34 -0
  136. helm/benchmark/metrics/medication_qa_metrics.py +15 -4
  137. helm/benchmark/metrics/mental_health_metrics.py +34 -0
  138. helm/benchmark/metrics/metric.py +3 -3
  139. helm/benchmark/metrics/mimic_rrs_metrics.py +34 -0
  140. helm/benchmark/metrics/mimiciv_billing_code_metrics.py +96 -0
  141. helm/benchmark/metrics/mtsamples_procedures_metrics.py +34 -0
  142. helm/benchmark/metrics/mtsamples_replicate_metrics.py +34 -0
  143. helm/benchmark/metrics/nltk_helper.py +32 -0
  144. helm/benchmark/metrics/numeracy_metrics.py +4 -4
  145. helm/benchmark/metrics/omni_math_metrics.py +32 -0
  146. helm/benchmark/metrics/output_processing_metric.py +60 -0
  147. helm/benchmark/metrics/output_processors.py +15 -0
  148. helm/benchmark/metrics/paraphrase_generation_metrics.py +2 -2
  149. helm/benchmark/metrics/ranking_metrics.py +3 -3
  150. helm/benchmark/metrics/reference_metric.py +3 -3
  151. helm/benchmark/metrics/safety_metrics.py +39 -17
  152. helm/benchmark/metrics/{bhasa_metrics.py → seahelm_metrics.py} +3 -3
  153. helm/benchmark/metrics/seahelm_metrics_specs.py +10 -0
  154. helm/benchmark/metrics/spider_metrics.py +7 -0
  155. helm/benchmark/metrics/starr_patient_instructions_metrics.py +34 -0
  156. helm/benchmark/metrics/statistic.py +1 -1
  157. helm/benchmark/metrics/summac/model_summac.py +1 -1
  158. helm/benchmark/metrics/summarization_critique_metrics.py +4 -4
  159. helm/benchmark/metrics/summarization_metrics.py +19 -9
  160. helm/benchmark/metrics/test_bias_metrics.py +5 -1
  161. helm/benchmark/metrics/test_classification_metrics.py +140 -68
  162. helm/benchmark/metrics/test_evaluate_reference_metrics.py +15 -0
  163. helm/benchmark/metrics/test_metric.py +1 -1
  164. helm/benchmark/metrics/test_statistic.py +2 -2
  165. helm/benchmark/metrics/tokens/ai21_token_cost_estimator.py +1 -1
  166. helm/benchmark/metrics/tokens/auto_token_cost_estimator.py +6 -6
  167. helm/benchmark/metrics/tokens/cohere_token_cost_estimator.py +1 -1
  168. helm/benchmark/metrics/tokens/free_token_cost_estimator.py +1 -1
  169. helm/benchmark/metrics/tokens/gooseai_token_cost_estimator.py +1 -1
  170. helm/benchmark/metrics/tokens/openai_token_cost_estimator.py +1 -1
  171. helm/benchmark/metrics/tokens/test_ai21_token_cost_estimator.py +1 -1
  172. helm/benchmark/metrics/tokens/test_openai_token_cost_estimator.py +1 -1
  173. helm/benchmark/metrics/toxicity_metrics.py +4 -4
  174. helm/benchmark/metrics/unitxt_metrics.py +21 -4
  175. helm/benchmark/metrics/vision_language/image_metrics.py +7 -3
  176. helm/benchmark/metrics/wildbench_metrics.py +34 -0
  177. helm/benchmark/model_metadata_registry.py +16 -0
  178. helm/benchmark/presentation/create_plots.py +1 -1
  179. helm/benchmark/presentation/schema.py +3 -0
  180. helm/benchmark/presentation/summarize.py +119 -256
  181. helm/benchmark/presentation/test_summarize.py +145 -3
  182. helm/benchmark/presentation/torr_robustness_summarizer.py +178 -0
  183. helm/benchmark/reeval_run.py +203 -0
  184. helm/benchmark/reeval_runner.py +355 -0
  185. helm/benchmark/run.py +8 -17
  186. helm/benchmark/run_expander.py +105 -8
  187. helm/benchmark/run_spec_factory.py +12 -0
  188. helm/benchmark/run_specs/air_bench_run_specs.py +21 -3
  189. helm/benchmark/run_specs/audio_run_specs.py +613 -0
  190. helm/benchmark/run_specs/call_center_run_specs.py +49 -0
  191. helm/benchmark/run_specs/capabilities_run_specs.py +308 -0
  192. helm/benchmark/run_specs/classic_run_specs.py +1 -69
  193. helm/benchmark/run_specs/enem_challenge_specs.py +31 -0
  194. helm/benchmark/run_specs/enterprise_run_specs.py +260 -0
  195. helm/benchmark/run_specs/experimental_run_specs.py +112 -3
  196. helm/benchmark/run_specs/finance_run_specs.py +6 -2
  197. helm/benchmark/run_specs/imdb_ptbr_run_specs.py +30 -0
  198. helm/benchmark/run_specs/lite_run_specs.py +2 -2
  199. helm/benchmark/run_specs/long_context_run_specs.py +89 -0
  200. helm/benchmark/run_specs/medhelm_run_specs.py +1155 -0
  201. helm/benchmark/run_specs/mmlu_clinical_afr_run_specs.py +49 -0
  202. helm/benchmark/run_specs/oab_exams_specs.py +32 -0
  203. helm/benchmark/run_specs/safety_run_specs.py +37 -0
  204. helm/benchmark/run_specs/{bhasa_run_specs.py → seahelm_run_specs.py} +66 -52
  205. helm/benchmark/run_specs/sql_run_specs.py +54 -0
  206. helm/benchmark/run_specs/tweetsentbr_run_specs.py +32 -0
  207. helm/benchmark/run_specs/unitxt_run_specs.py +14 -5
  208. helm/benchmark/run_specs/vlm_run_specs.py +83 -5
  209. helm/benchmark/run_specs/winogrande_afr_run_specs.py +47 -0
  210. helm/benchmark/scenarios/aci_bench_scenario.py +120 -0
  211. helm/benchmark/scenarios/air_bench_scenario.py +6 -1
  212. helm/benchmark/scenarios/anthropic_hh_rlhf_scenario.py +5 -3
  213. helm/benchmark/scenarios/anthropic_red_team_scenario.py +1 -1
  214. helm/benchmark/scenarios/audio_language/__init__.py +0 -0
  215. helm/benchmark/scenarios/audio_language/air_bench_chat_scenario.py +128 -0
  216. helm/benchmark/scenarios/audio_language/air_bench_foundation_scenario.py +154 -0
  217. helm/benchmark/scenarios/audio_language/ami_scenario.py +96 -0
  218. helm/benchmark/scenarios/audio_language/audio_mnist_scenario.py +62 -0
  219. helm/benchmark/scenarios/audio_language/audio_pairs_scenario.py +62 -0
  220. helm/benchmark/scenarios/audio_language/audiocaps_scenario.py +59 -0
  221. helm/benchmark/scenarios/audio_language/casual_conversations2_scenario.py +152 -0
  222. helm/benchmark/scenarios/audio_language/common_voice_15_scenario.py +99 -0
  223. helm/benchmark/scenarios/audio_language/covost2_scenario.py +163 -0
  224. helm/benchmark/scenarios/audio_language/fleurs_fairness_scenario.py +83 -0
  225. helm/benchmark/scenarios/audio_language/fleurs_scenario.py +312 -0
  226. helm/benchmark/scenarios/audio_language/iemocap_audio_scenario.py +83 -0
  227. helm/benchmark/scenarios/audio_language/librispeech_fairness_scenario.py +96 -0
  228. helm/benchmark/scenarios/audio_language/librispeech_scenario.py +80 -0
  229. helm/benchmark/scenarios/audio_language/meld_audio_scenario.py +113 -0
  230. helm/benchmark/scenarios/audio_language/multilingual_librispeech_scenario.py +80 -0
  231. helm/benchmark/scenarios/audio_language/mustard_scenario.py +142 -0
  232. helm/benchmark/scenarios/audio_language/mutox_scenario.py +254 -0
  233. helm/benchmark/scenarios/audio_language/parade_scenario.py +97 -0
  234. helm/benchmark/scenarios/audio_language/speech_robust_bench_scenario.py +124 -0
  235. helm/benchmark/scenarios/audio_language/vocal_sound_scenario.py +69 -0
  236. helm/benchmark/scenarios/audio_language/voice_jailbreak_attacks_scenario.py +87 -0
  237. helm/benchmark/scenarios/audio_language/voxceleb2_scenario.py +106 -0
  238. helm/benchmark/scenarios/autobencher_capabilities_scenario.py +68 -0
  239. helm/benchmark/scenarios/autobencher_safety_scenario.py +51 -0
  240. helm/benchmark/scenarios/babi_qa_scenario.py +1 -1
  241. helm/benchmark/scenarios/banking77_scenario.py +6 -1
  242. helm/benchmark/scenarios/bbq_scenario.py +1 -1
  243. helm/benchmark/scenarios/big_bench_scenario.py +11 -1
  244. helm/benchmark/scenarios/bigcodebench_scenario.py +58 -0
  245. helm/benchmark/scenarios/bird_sql_scenario.py +94 -0
  246. helm/benchmark/scenarios/bird_sql_scenario_helper.py +118 -0
  247. helm/benchmark/scenarios/blimp_scenario.py +1 -1
  248. helm/benchmark/scenarios/bold_scenario.py +1 -1
  249. helm/benchmark/scenarios/boolq_scenario.py +1 -1
  250. helm/benchmark/scenarios/casehold_scenario.py +79 -0
  251. helm/benchmark/scenarios/chw_care_plan_scenario.py +105 -0
  252. helm/benchmark/scenarios/civil_comments_scenario.py +1 -1
  253. helm/benchmark/scenarios/clear_scenario.py +153 -0
  254. helm/benchmark/scenarios/cleva_scenario.py +2 -2
  255. helm/benchmark/scenarios/code_scenario.py +17 -4
  256. helm/benchmark/scenarios/commonsense_scenario.py +1 -1
  257. helm/benchmark/scenarios/conv_fin_qa_calc_scenario.py +97 -0
  258. helm/benchmark/scenarios/copyright_scenario.py +1 -1
  259. helm/benchmark/scenarios/covid_dialog_scenario.py +10 -1
  260. helm/benchmark/scenarios/cti_to_mitre_scenario.py +240 -0
  261. helm/benchmark/scenarios/custom_mcqa_scenario.py +1 -1
  262. helm/benchmark/scenarios/czech_bank_qa_scenario.py +130 -0
  263. helm/benchmark/scenarios/decodingtrust_adv_demonstration_scenario.py +1 -1
  264. helm/benchmark/scenarios/decodingtrust_privacy_scenario.py +1 -1
  265. helm/benchmark/scenarios/decodingtrust_stereotype_bias_scenario.py +1 -1
  266. helm/benchmark/scenarios/decodingtrust_toxicity_prompts_scenario.py +1 -1
  267. helm/benchmark/scenarios/dialogue_scenarios.py +13 -2
  268. helm/benchmark/scenarios/dischargeme_scenario.py +157 -0
  269. helm/benchmark/scenarios/disinformation_scenario.py +10 -1
  270. helm/benchmark/scenarios/dyck_language_scenario.py +10 -1
  271. helm/benchmark/scenarios/echr_judgment_classification_scenario.py +113 -0
  272. helm/benchmark/scenarios/ehr_sql_scenario.py +131 -0
  273. helm/benchmark/scenarios/ehrshot_scenario.py +1546 -0
  274. helm/benchmark/scenarios/enem_challenge_scenario.py +58 -0
  275. helm/benchmark/scenarios/entity_data_imputation_scenario.py +11 -1
  276. helm/benchmark/scenarios/entity_matching_scenario.py +12 -2
  277. helm/benchmark/scenarios/financial_phrasebank_scenario.py +94 -0
  278. helm/benchmark/scenarios/gold_commodity_news_scenario.py +124 -0
  279. helm/benchmark/scenarios/gpqa_scenario.py +80 -0
  280. helm/benchmark/scenarios/grammar_scenario.py +2 -2
  281. helm/benchmark/scenarios/gsm_scenario.py +10 -1
  282. helm/benchmark/scenarios/harm_bench_gcg_transfer_scenario.py +50 -0
  283. helm/benchmark/scenarios/harm_bench_scenario.py +1 -1
  284. helm/benchmark/scenarios/headqa_scenario.py +131 -0
  285. helm/benchmark/scenarios/helpdesk_call_summarization_scenario.py +37 -0
  286. helm/benchmark/scenarios/ice_scenario.py +8 -4
  287. helm/benchmark/scenarios/ifeval_scenario.py +53 -0
  288. helm/benchmark/scenarios/imdb_ptbr_scenario.py +60 -0
  289. helm/benchmark/scenarios/imdb_scenario.py +11 -2
  290. helm/benchmark/scenarios/infinite_bench_sum_scenario.py +82 -0
  291. helm/benchmark/scenarios/interactive_qa_mmlu_scenario.py +2 -2
  292. helm/benchmark/scenarios/koala_scenario.py +1 -1
  293. helm/benchmark/scenarios/legal_contract_summarization_scenario.py +129 -0
  294. helm/benchmark/scenarios/legal_opinion_sentiment_classification_scenario.py +77 -0
  295. helm/benchmark/scenarios/legal_summarization_scenario.py +11 -1
  296. helm/benchmark/scenarios/legal_support_scenario.py +11 -1
  297. helm/benchmark/scenarios/legalbench_scenario.py +22 -3
  298. helm/benchmark/scenarios/lex_glue_scenario.py +12 -2
  299. helm/benchmark/scenarios/lextreme_scenario.py +11 -1
  300. helm/benchmark/scenarios/live_qa_scenario.py +1 -1
  301. helm/benchmark/scenarios/lm_entry_scenario.py +1 -1
  302. helm/benchmark/scenarios/lsat_qa_scenario.py +1 -1
  303. helm/benchmark/scenarios/math_scenario.py +9 -1
  304. helm/benchmark/scenarios/me_q_sum_scenario.py +10 -1
  305. helm/benchmark/scenarios/med_dialog_scenario.py +22 -24
  306. helm/benchmark/scenarios/med_mcqa_scenario.py +10 -1
  307. helm/benchmark/scenarios/med_paragraph_simplification_scenario.py +10 -1
  308. helm/benchmark/scenarios/med_qa_scenario.py +10 -1
  309. helm/benchmark/scenarios/medalign_scenario.py +88 -0
  310. helm/benchmark/scenarios/medalign_scenario_helper.py +429 -0
  311. helm/benchmark/scenarios/medbullets_scenario.py +140 -0
  312. helm/benchmark/scenarios/medcalc_bench_scenario.py +125 -0
  313. helm/benchmark/scenarios/medec_scenario.py +120 -0
  314. helm/benchmark/scenarios/medhallu_scenario.py +66 -0
  315. helm/benchmark/scenarios/medi_qa_scenario.py +105 -0
  316. helm/benchmark/scenarios/medication_qa_scenario.py +2 -2
  317. helm/benchmark/scenarios/mental_health_scenario.py +112 -0
  318. helm/benchmark/scenarios/mimic_bhc_scenario.py +98 -0
  319. helm/benchmark/scenarios/mimic_rrs_scenario.py +89 -0
  320. helm/benchmark/scenarios/mimiciv_billing_code_scenario.py +71 -0
  321. helm/benchmark/scenarios/mmlu_clinical_afr_scenario.py +74 -0
  322. helm/benchmark/scenarios/mmlu_pro_scenario.py +95 -0
  323. helm/benchmark/scenarios/mmlu_scenario.py +11 -1
  324. helm/benchmark/scenarios/msmarco_scenario.py +1 -1
  325. helm/benchmark/scenarios/mtsamples_procedures_scenario.py +141 -0
  326. helm/benchmark/scenarios/mtsamples_replicate_scenario.py +141 -0
  327. helm/benchmark/scenarios/n2c2_ct_matching_scenario.py +271 -0
  328. helm/benchmark/scenarios/narrativeqa_scenario.py +1 -1
  329. helm/benchmark/scenarios/natural_qa_scenario.py +1 -1
  330. helm/benchmark/scenarios/newsqa_scenario.py +1 -1
  331. helm/benchmark/scenarios/numeracy_scenario.py +10 -1
  332. helm/benchmark/scenarios/oab_exams_scenario.py +57 -0
  333. helm/benchmark/scenarios/omni_math_scenario.py +53 -0
  334. helm/benchmark/scenarios/open_assistant_scenario.py +11 -2
  335. helm/benchmark/scenarios/opinions_qa_scenario.py +1 -1
  336. helm/benchmark/scenarios/pubmed_qa_scenario.py +54 -43
  337. helm/benchmark/scenarios/quac_scenario.py +10 -1
  338. helm/benchmark/scenarios/race_based_med_scenario.py +142 -0
  339. helm/benchmark/scenarios/raft_scenario.py +18 -3
  340. helm/benchmark/scenarios/real_toxicity_prompts_scenario.py +1 -1
  341. helm/benchmark/scenarios/ruler_qa_scenario_helper.py +171 -0
  342. helm/benchmark/scenarios/ruler_qa_scenarios.py +88 -0
  343. helm/benchmark/scenarios/scenario.py +9 -1
  344. helm/benchmark/scenarios/{bhasa_scenario.py → seahelm_scenario.py} +233 -84
  345. helm/benchmark/scenarios/self_instruct_scenario.py +1 -1
  346. helm/benchmark/scenarios/shc_bmt_scenario.py +69 -0
  347. helm/benchmark/scenarios/shc_cdi_scenario.py +70 -0
  348. helm/benchmark/scenarios/shc_conf_scenario.py +70 -0
  349. helm/benchmark/scenarios/shc_ent_scenario.py +72 -0
  350. helm/benchmark/scenarios/shc_gip_scenario.py +66 -0
  351. helm/benchmark/scenarios/shc_ptbm_scenario.py +76 -0
  352. helm/benchmark/scenarios/shc_sei_scenario.py +89 -0
  353. helm/benchmark/scenarios/shc_sequoia_scenario.py +69 -0
  354. helm/benchmark/scenarios/simple_safety_tests_scenario.py +1 -1
  355. helm/benchmark/scenarios/spider_scenario.py +91 -0
  356. helm/benchmark/scenarios/starr_patient_instructions_scenario.py +90 -0
  357. helm/benchmark/scenarios/summarization_scenario.py +11 -1
  358. helm/benchmark/scenarios/sumosum_scenario.py +157 -0
  359. helm/benchmark/scenarios/synthetic_efficiency_scenario.py +1 -1
  360. helm/benchmark/scenarios/synthetic_reasoning_natural_scenario.py +11 -1
  361. helm/benchmark/scenarios/synthetic_reasoning_scenario.py +11 -1
  362. helm/benchmark/scenarios/test_bigcodebench_scenario.py +26 -0
  363. helm/benchmark/scenarios/test_czech_bank_qa_scenario.py +18 -0
  364. helm/benchmark/scenarios/test_enem_challenge_scenario.py +53 -0
  365. helm/benchmark/scenarios/test_ewok_scenario.py +6 -2
  366. helm/benchmark/scenarios/test_gold_commodity_news_scenario.py +18 -0
  367. helm/benchmark/scenarios/test_gpqa_scenario.py +44 -0
  368. helm/benchmark/scenarios/test_ifeval_scenario.py +36 -0
  369. helm/benchmark/scenarios/test_imdb_ptbr_scenario.py +27 -0
  370. helm/benchmark/scenarios/test_infinite_bench_sum_scenario.py +46 -0
  371. helm/benchmark/scenarios/test_math_scenario.py +1 -0
  372. helm/benchmark/scenarios/test_mmlu_clinical_afr_scenario.py +21 -0
  373. helm/benchmark/scenarios/test_mmlu_pro_scenario.py +53 -0
  374. helm/benchmark/scenarios/test_oab_exams_scenario.py +51 -0
  375. helm/benchmark/scenarios/test_omni_math_scenario.py +27 -0
  376. helm/benchmark/scenarios/test_tweetsentbr_scenario.py +24 -0
  377. helm/benchmark/scenarios/test_wildbench_scenario.py +15 -0
  378. helm/benchmark/scenarios/test_winogrande_afr_scenario.py +19 -0
  379. helm/benchmark/scenarios/thai_exam_scenario.py +10 -1
  380. helm/benchmark/scenarios/the_pile_scenario.py +1 -1
  381. helm/benchmark/scenarios/truthful_qa_scenario.py +10 -1
  382. helm/benchmark/scenarios/tweetsentbr_scenario.py +66 -0
  383. helm/benchmark/scenarios/twitter_aae_scenario.py +1 -1
  384. helm/benchmark/scenarios/unitxt_scenario.py +8 -2
  385. helm/benchmark/scenarios/verifiability_judgment_scenario.py +1 -1
  386. helm/benchmark/scenarios/vicuna_scenario.py +1 -1
  387. helm/benchmark/scenarios/vision_language/blink_scenario.py +140 -0
  388. helm/benchmark/scenarios/vision_language/mm_star_scenario.py +95 -0
  389. helm/benchmark/scenarios/vision_language/vqa_rad_scenario.py +88 -0
  390. helm/benchmark/scenarios/wikifact_scenario.py +11 -1
  391. helm/benchmark/scenarios/wikitext_103_scenario.py +1 -1
  392. helm/benchmark/scenarios/wildbench_scenario.py +83 -0
  393. helm/benchmark/scenarios/winogrande_afr_scenario.py +78 -0
  394. helm/benchmark/scenarios/wmt_14_scenario.py +14 -2
  395. helm/benchmark/scenarios/xstest_scenario.py +1 -1
  396. helm/benchmark/server.py +11 -0
  397. helm/benchmark/slurm_runner.py +1 -1
  398. helm/benchmark/static/schema_audio.yaml +752 -0
  399. helm/benchmark/static/schema_autobencher.yaml +150 -0
  400. helm/benchmark/static/schema_call_center.yaml +97 -60
  401. helm/benchmark/static/schema_capabilities.yaml +254 -0
  402. helm/benchmark/static/schema_czech_bank.yaml +148 -0
  403. helm/benchmark/static/schema_enem_challenge.yaml +146 -0
  404. helm/benchmark/static/schema_enterprise.yaml +298 -0
  405. helm/benchmark/static/schema_finance.yaml +14 -12
  406. helm/benchmark/static/schema_heim.yaml +1389 -0
  407. helm/benchmark/static/schema_legal.yaml +566 -0
  408. helm/benchmark/static/{schema_medical.yaml → schema_long_context.yaml} +67 -82
  409. helm/benchmark/static/schema_medhelm.yaml +1081 -0
  410. helm/benchmark/static/schema_mmlu_winogrande_afr.yaml +1045 -0
  411. helm/benchmark/static/schema_safety.yaml +42 -6
  412. helm/benchmark/static/{schema_bhasa.yaml → schema_seahelm.yaml} +40 -26
  413. helm/benchmark/static/schema_social_audio.yaml +224 -0
  414. helm/benchmark/static/schema_sql.yaml +171 -0
  415. helm/benchmark/static/{schema_tables.yaml → schema_torr.yaml} +187 -30
  416. helm/benchmark/static/schema_tweetsentbr.yaml +146 -0
  417. helm/benchmark/static/schema_vhelm.yaml +151 -47
  418. helm/benchmark/static_build/assets/helm-safety-2907a7b6.png +0 -0
  419. helm/benchmark/static_build/assets/index-262903c1.js +10 -0
  420. helm/benchmark/static_build/assets/index-42060d71.css +1 -0
  421. helm/benchmark/static_build/assets/medhelm-overview-3ddfcd65.png +0 -0
  422. helm/benchmark/static_build/assets/{react-d4a0b69b.js → react-f82877fd.js} +1 -1
  423. helm/benchmark/static_build/assets/{recharts-6d337683.js → recharts-4037aff0.js} +1 -1
  424. helm/benchmark/static_build/assets/{tremor-54a99cc4.js → tremor-9cefc3c5.js} +1 -1
  425. helm/benchmark/static_build/assets/vhelm-aspects-1437d673.png +0 -0
  426. helm/benchmark/static_build/assets/vhelm-framework-a1ca3f3f.png +0 -0
  427. helm/benchmark/static_build/assets/vhelm-model-8afb7616.png +0 -0
  428. helm/benchmark/static_build/config.js +1 -1
  429. helm/benchmark/static_build/index.html +5 -5
  430. helm/benchmark/window_services/default_window_service.py +1 -1
  431. helm/benchmark/window_services/encoder_decoder_window_service.py +1 -1
  432. helm/benchmark/window_services/ice_window_service.py +1 -1
  433. helm/benchmark/window_services/image_generation/lexica_search_window_service.py +1 -1
  434. helm/benchmark/window_services/image_generation/openai_dalle_window_service.py +1 -1
  435. helm/benchmark/window_services/local_window_service.py +2 -2
  436. helm/benchmark/window_services/test_anthropic_window_service.py +3 -3
  437. helm/benchmark/window_services/test_bloom_window_service.py +3 -3
  438. helm/benchmark/window_services/test_gpt2_window_service.py +7 -2
  439. helm/benchmark/window_services/test_gpt4_window_service.py +8 -3
  440. helm/benchmark/window_services/test_gptj_window_service.py +8 -3
  441. helm/benchmark/window_services/test_gptneox_window_service.py +3 -3
  442. helm/benchmark/window_services/test_openai_window_service.py +8 -3
  443. helm/benchmark/window_services/test_opt_window_service.py +3 -3
  444. helm/benchmark/window_services/test_palmyra_window_service.py +3 -3
  445. helm/benchmark/window_services/test_t0pp_window_service.py +3 -3
  446. helm/benchmark/window_services/test_t511b_window_service.py +3 -3
  447. helm/benchmark/window_services/test_ul2_window_service.py +3 -3
  448. helm/benchmark/window_services/test_utils.py +1 -1
  449. helm/benchmark/window_services/test_yalm_window_service.py +3 -3
  450. helm/benchmark/window_services/tokenizer_service.py +0 -5
  451. helm/benchmark/window_services/yalm_window_service.py +1 -1
  452. helm/clients/ai21_client.py +3 -3
  453. helm/clients/aleph_alpha_client.py +1 -1
  454. helm/clients/audio_language/__init__.py +0 -0
  455. helm/clients/audio_language/diva_llama_client.py +118 -0
  456. helm/clients/audio_language/llama_omni_client.py +198 -0
  457. helm/clients/audio_language/qwen2_audiolm_client.py +188 -0
  458. helm/clients/audio_language/qwen_audiolm_client.py +150 -0
  459. helm/clients/auto_client.py +4 -2
  460. helm/clients/azure_openai_client.py +55 -0
  461. helm/clients/bedrock_client.py +201 -7
  462. helm/clients/bedrock_utils.py +33 -0
  463. helm/clients/clip_scorers/clip_scorer.py +1 -1
  464. helm/clients/clip_scorers/multilingual_clip_scorer.py +1 -1
  465. helm/clients/cohere_client.py +3 -3
  466. helm/clients/google_client.py +1 -1
  467. helm/clients/http_model_client.py +1 -1
  468. helm/clients/huggingface_client.py +10 -18
  469. helm/clients/ibm_client.py +267 -0
  470. helm/clients/image_generation/adobe_vision_client.py +1 -1
  471. helm/clients/image_generation/aleph_alpha_image_generation_client.py +1 -1
  472. helm/clients/image_generation/cogview2/sr_pipeline/__init__.py +3 -3
  473. helm/clients/image_generation/cogview2/sr_pipeline/direct_sr.py +5 -2
  474. helm/clients/image_generation/cogview2/sr_pipeline/iterative_sr.py +5 -2
  475. helm/clients/image_generation/cogview2/sr_pipeline/sr_group.py +2 -2
  476. helm/clients/image_generation/cogview2_client.py +1 -1
  477. helm/clients/image_generation/dalle2_client.py +1 -1
  478. helm/clients/image_generation/dalle3_client.py +2 -2
  479. helm/clients/image_generation/dalle_mini/__init__.py +1 -1
  480. helm/clients/image_generation/dalle_mini/data.py +1 -1
  481. helm/clients/image_generation/dalle_mini/model/__init__.py +5 -5
  482. helm/clients/image_generation/dalle_mini/model/configuration.py +1 -1
  483. helm/clients/image_generation/dalle_mini/model/modeling.py +2 -2
  484. helm/clients/image_generation/dalle_mini/model/processor.py +4 -4
  485. helm/clients/image_generation/dalle_mini/model/tokenizer.py +1 -1
  486. helm/clients/image_generation/dalle_mini/vqgan_jax/__init__.py +1 -1
  487. helm/clients/image_generation/dalle_mini/vqgan_jax/convert_pt_model_to_jax.py +2 -2
  488. helm/clients/image_generation/dalle_mini/vqgan_jax/modeling_flax_vqgan.py +1 -1
  489. helm/clients/image_generation/dalle_mini_client.py +1 -1
  490. helm/clients/image_generation/deep_floyd_client.py +1 -1
  491. helm/clients/image_generation/huggingface_diffusers_client.py +1 -1
  492. helm/clients/image_generation/lexica_client.py +1 -1
  493. helm/clients/image_generation/mindalle/models/__init__.py +6 -6
  494. helm/clients/image_generation/mindalle/models/stage1/vqgan.py +1 -1
  495. helm/clients/image_generation/mindalle/models/stage2/transformer.py +1 -1
  496. helm/clients/image_generation/mindalle/utils/__init__.py +3 -3
  497. helm/clients/image_generation/mindalle_client.py +1 -1
  498. helm/clients/image_generation/together_image_generation_client.py +1 -1
  499. helm/clients/lit_gpt_client.py +2 -2
  500. helm/clients/mistral_client.py +62 -18
  501. helm/clients/nvidia_nim_client.py +0 -3
  502. helm/clients/openai_client.py +255 -21
  503. helm/clients/palmyra_client.py +2 -6
  504. helm/clients/reka_client.py +1 -1
  505. helm/clients/stanfordhealthcare_azure_openai_client.py +58 -0
  506. helm/clients/stanfordhealthcare_claude_client.py +31 -0
  507. helm/clients/stanfordhealthcare_google_client.py +43 -0
  508. helm/clients/stanfordhealthcare_http_model_client.py +93 -0
  509. helm/clients/stanfordhealthcare_openai_client.py +62 -0
  510. helm/clients/stanfordhealthcare_shc_openai_client.py +42 -0
  511. helm/clients/test_client.py +1 -1
  512. helm/clients/test_together_client.py +6 -1
  513. helm/clients/together_client.py +69 -7
  514. helm/clients/upstage_client.py +23 -0
  515. helm/clients/vertexai_client.py +39 -13
  516. helm/clients/vision_language/open_flamingo/__init__.py +2 -2
  517. helm/clients/vision_language/open_flamingo/src/factory.py +3 -3
  518. helm/clients/vision_language/open_flamingo/src/flamingo.py +2 -2
  519. helm/clients/vision_language/open_flamingo/src/flamingo_lm.py +2 -2
  520. helm/clients/vision_language/qwen2_vlm_client.py +175 -0
  521. helm/clients/vllm_client.py +4 -6
  522. helm/clients/yi_client.py +0 -3
  523. helm/common/audio_utils.py +111 -0
  524. helm/common/cache.py +8 -30
  525. helm/common/file_caches/local_file_cache.py +1 -1
  526. helm/common/file_caches/test_local_file_cache.py +1 -1
  527. helm/common/images_utils.py +2 -2
  528. helm/common/key_value_store.py +9 -9
  529. helm/common/media_object.py +2 -2
  530. helm/common/mongo_key_value_store.py +3 -3
  531. helm/common/multimodal_request_utils.py +26 -0
  532. helm/common/reeval_parameters.py +12 -0
  533. helm/common/request.py +6 -2
  534. helm/common/response_format.py +18 -0
  535. helm/common/test_cache.py +1 -48
  536. helm/common/test_media_object.py +1 -1
  537. helm/common/tokenization_request.py +0 -9
  538. helm/config/model_deployments.yaml +1258 -33
  539. helm/config/model_metadata.yaml +1110 -41
  540. helm/config/tokenizer_configs.yaml +403 -3
  541. helm/proxy/cli.py +2 -2
  542. helm/proxy/example_queries.py +1 -1
  543. helm/proxy/server.py +11 -13
  544. helm/proxy/services/remote_service.py +1 -7
  545. helm/proxy/services/server_service.py +6 -19
  546. helm/proxy/services/service.py +0 -6
  547. helm/proxy/services/test_remote_service.py +2 -2
  548. helm/proxy/services/test_service.py +1 -1
  549. helm/proxy/static/general.js +122 -0
  550. helm/proxy/static/help.html +99 -0
  551. helm/proxy/static/index.css +57 -0
  552. helm/proxy/static/index.html +40 -0
  553. helm/proxy/static/index.js +456 -0
  554. helm/proxy/static/info-icon.png +0 -0
  555. helm/proxy/test_retry.py +1 -1
  556. helm/proxy/token_counters/auto_token_counter.py +1 -1
  557. helm/tokenizers/aleph_alpha_tokenizer.py +1 -1
  558. helm/tokenizers/caching_tokenizer.py +2 -30
  559. helm/tokenizers/http_model_tokenizer.py +1 -1
  560. helm/tokenizers/huggingface_tokenizer.py +2 -2
  561. helm/tokenizers/lit_gpt_tokenizer.py +1 -1
  562. helm/tokenizers/test_anthropic_tokenizer.py +6 -2
  563. helm/tokenizers/test_huggingface_tokenizer.py +1 -1
  564. helm/tokenizers/test_yalm_tokenizer.py +1 -1
  565. helm/tokenizers/tiktoken_tokenizer.py +1 -1
  566. helm/tokenizers/tokenizer.py +3 -1
  567. helm/tokenizers/yalm_tokenizer.py +3 -3
  568. helm/tokenizers/yalm_tokenizer_data/test_yalm_tokenizer.py +1 -1
  569. crfm_helm-0.5.3.dist-info/METADATA +0 -355
  570. crfm_helm-0.5.3.dist-info/RECORD +0 -699
  571. helm/benchmark/data_overlap/data_overlap_spec.py +0 -86
  572. helm/benchmark/data_overlap/export_scenario_text.py +0 -119
  573. helm/benchmark/data_overlap/light_scenario.py +0 -60
  574. helm/benchmark/metrics/bhasa_metrics_specs.py +0 -10
  575. helm/benchmark/static_build/assets/01-694cb9b7.png +0 -0
  576. helm/benchmark/static_build/assets/accenture-6f97eeda.png +0 -0
  577. helm/benchmark/static_build/assets/ai21-0eb91ec3.png +0 -0
  578. helm/benchmark/static_build/assets/aisingapore-6dfc9acf.png +0 -0
  579. helm/benchmark/static_build/assets/aleph-alpha-7ce10034.png +0 -0
  580. helm/benchmark/static_build/assets/anthropic-70d8bc39.png +0 -0
  581. helm/benchmark/static_build/assets/bigscience-7f0400c0.png +0 -0
  582. helm/benchmark/static_build/assets/cohere-3550c6cb.png +0 -0
  583. helm/benchmark/static_build/assets/cresta-9e22b983.png +0 -0
  584. helm/benchmark/static_build/assets/cuhk-8c5631e9.png +0 -0
  585. helm/benchmark/static_build/assets/eleutherai-b9451114.png +0 -0
  586. helm/benchmark/static_build/assets/google-06d997ad.png +0 -0
  587. helm/benchmark/static_build/assets/index-05c76bb1.css +0 -1
  588. helm/benchmark/static_build/assets/index-58f97dcd.js +0 -10
  589. helm/benchmark/static_build/assets/meta-5580e9f1.png +0 -0
  590. helm/benchmark/static_build/assets/microsoft-f5ee5016.png +0 -0
  591. helm/benchmark/static_build/assets/mistral-18e1be23.png +0 -0
  592. helm/benchmark/static_build/assets/nvidia-86fa75c1.png +0 -0
  593. helm/benchmark/static_build/assets/openai-3f8653e4.png +0 -0
  594. helm/benchmark/static_build/assets/scb10x-204bd786.png +0 -0
  595. helm/benchmark/static_build/assets/tii-24de195c.png +0 -0
  596. helm/benchmark/static_build/assets/together-a665a35b.png +0 -0
  597. helm/benchmark/static_build/assets/tsinghua-keg-97d4b395.png +0 -0
  598. helm/benchmark/static_build/assets/vhelm-framework-cde7618a.png +0 -0
  599. helm/benchmark/static_build/assets/vhelm-model-6d812526.png +0 -0
  600. helm/benchmark/static_build/assets/wellsfargo-a86a6c4a.png +0 -0
  601. helm/benchmark/static_build/assets/yandex-38e09d70.png +0 -0
  602. helm/tokenizers/anthropic_tokenizer.py +0 -52
  603. {crfm_helm-0.5.3.dist-info → crfm_helm-0.5.5.dist-info}/entry_points.txt +0 -0
  604. {crfm_helm-0.5.3.dist-info → crfm_helm-0.5.5.dist-info/licenses}/LICENSE +0 -0
  605. {crfm_helm-0.5.3.dist-info → crfm_helm-0.5.5.dist-info}/top_level.txt +0 -0
  606. /helm/benchmark/{data_overlap → metrics/ifeval}/__init__.py +0 -0
@@ -0,0 +1,1574 @@
1
+ # flake8: noqa
2
+ # type: ignore
3
+ # fmt: off
4
+ # The following code was reproduced with minor modifications to `import` statements from the following URL:
5
+ # https://github.com/google-research/google-research/blob/c7f60c013623e613732a096e2a0c2872491ec912/instruction_following_eval/instructions.py
6
+
7
+ # coding=utf-8
8
+ # Copyright 2023 The Google Research Authors.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+ """Library of instructions."""
23
+ import collections
24
+ import json
25
+ import random
26
+ import re
27
+ import string
28
+ from typing import Dict, Optional, Sequence, Union
29
+
30
+ from absl import logging
31
+ import langdetect
32
+
33
+ import helm.benchmark.metrics.ifeval.instructions_util as instructions_util
34
+
35
+ from helm.benchmark.metrics.ifeval.instructions_util import LANGUAGE_CODES
36
+
37
+
38
+ _InstructionArgsDtype = Optional[Dict[str, Union[int, str, Sequence[str]]]]
39
+
40
+ _LANGUAGES = LANGUAGE_CODES
41
+
42
+ # The relational operation for comparison.
43
+ _COMPARISON_RELATION = ("less than", "at least")
44
+
45
+ # The maximum number of sentences.
46
+ _MAX_NUM_SENTENCES = 20
47
+
48
+ # The number of placeholders.
49
+ _NUM_PLACEHOLDERS = 4
50
+
51
+ # The number of bullet lists.
52
+ _NUM_BULLETS = 5
53
+
54
+ # The options of constrained response.
55
+ _CONSTRAINED_RESPONSE_OPTIONS = (
56
+ "My answer is yes.", "My answer is no.", "My answer is maybe.")
57
+
58
+ # The options of starter keywords.
59
+ _STARTER_OPTIONS = ("I would say", "My answer is", "I believe",
60
+ "In my opinion", "I think", "I reckon", "I feel",
61
+ "From my perspective", "As I see it", "According to me",
62
+ "As far as I'm concerned", "To my understanding",
63
+ "In my view", "My take on it is", "As per my perception")
64
+
65
+ # The options of ending keywords.
66
+ # TODO(jeffreyzhou) add more ending options
67
+ _ENDING_OPTIONS = ("Any other questions?",
68
+ "Is there anything else I can help with?")
69
+
70
+ # The number of highlighted sections.
71
+ _NUM_HIGHLIGHTED_SECTIONS = 4
72
+
73
+ # The section spliter.
74
+ _SECTION_SPLITER = ("Section", "SECTION")
75
+
76
+ # The number of sections.
77
+ _NUM_SECTIONS = 5
78
+
79
+ # The number of paragraphs.
80
+ _NUM_PARAGRAPHS = 5
81
+
82
+ # The postscript marker.
83
+ _POSTSCRIPT_MARKER = ("P.S.", "P.P.S")
84
+
85
+ # The number of keywords.
86
+ _NUM_KEYWORDS = 2
87
+
88
+ # The occurrences of a single keyword.
89
+ _KEYWORD_FREQUENCY = 3
90
+
91
+ # The occurrences of a single letter.
92
+ _LETTER_FREQUENCY = 10
93
+
94
+ # The occurrences of words with all capital letters.
95
+ _ALL_CAPITAL_WORD_FREQUENCY = 20
96
+
97
+ # The number of words in the response.
98
+ _NUM_WORDS_LOWER_LIMIT = 100
99
+ _NUM_WORDS_UPPER_LIMIT = 500
100
+
101
+
102
+ class Instruction:
103
+ """An instruction template."""
104
+
105
+ def __init__(self, instruction_id):
106
+ self.id = instruction_id
107
+
108
+ def build_description(self, **kwargs):
109
+ raise NotImplementedError("`build_description` not implemented.")
110
+
111
+ def get_instruction_args(self):
112
+ raise NotImplementedError("`get_instruction_args` not implemented.")
113
+
114
+ def get_instruction_args_keys(self):
115
+ raise NotImplementedError("`get_instruction_args_keys` not implemented.")
116
+
117
+ def check_following(self, value):
118
+ raise NotImplementedError("`check_following` not implemented.")
119
+
120
+
121
+ class ResponseLanguageChecker(Instruction):
122
+ """Check the language of the entire response."""
123
+
124
+ def build_description(self, *, language = None):
125
+ """Build the instruction description.
126
+
127
+ Args:
128
+ language: A string representing the expected language of the response. The
129
+ language has to comply to the 97 types defined in
130
+ `langid.py` (https://pypi.org/project/langid/1.1.5/), which follows
131
+ ISO 639-1 codes (https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes);
132
+ for example, `en` for English, `zh` for Chinese, `fr` for French.
133
+
134
+ Returns:
135
+ A string representing the instruction description.
136
+ """
137
+ self._language = language
138
+ if self._language is None:
139
+ self._language = random.choice(list(_LANGUAGES.keys()))
140
+ # TODO(tianjianlu): opens the description generation to more choices.
141
+ self._description_pattern = (
142
+ "Your ENTIRE response should be in {language} language, no other " +
143
+ "language is allowed.")
144
+ return self._description_pattern.format(language=_LANGUAGES[self._language])
145
+
146
+ def get_instruction_args(self):
147
+ """Returns the keyward args of `build_description`."""
148
+ return {"language": self._language}
149
+
150
+ def get_instruction_args_keys(self):
151
+ """Returns the args keys of `build_description`."""
152
+ return ["language"]
153
+
154
+ def check_following(self, value):
155
+ """Check if the language of the entire response follows the instruction.
156
+
157
+ Args:
158
+ value: A string representing the response.
159
+
160
+ Returns:
161
+ True if the language of `value` follows instruction; otherwise False.
162
+ """
163
+ assert isinstance(value, str)
164
+
165
+ try:
166
+ return langdetect.detect(value) == self._language
167
+ except langdetect.LangDetectException as e:
168
+ # Count as instruction is followed.
169
+ logging.error(
170
+ "Unable to detect language for text %s due to %s", value, e
171
+ ) # refex: disable=pytotw.037
172
+ return True
173
+
174
+
175
+ class NumberOfSentences(Instruction):
176
+ """Check the number of sentences."""
177
+
178
+ def build_description(self, *, num_sentences = None,
179
+ relation = None):
180
+ """Build the instruction description.
181
+
182
+ Args:
183
+ num_sentences: An integer specifying the number of sentences as a
184
+ threshold.
185
+ relation: A string in (`less than`, `at least`), defining the relational
186
+ operator for comparison.
187
+ Two relational comparisons are supported for now:
188
+ if 'less than', the actual number of sentences < the threshold;
189
+ if 'at least', the actual number of sentences >= the threshold.
190
+
191
+ Returns:
192
+ A string representing the instruction description.
193
+ """
194
+ # The number of sentences as a threshold for comparison.
195
+ self._num_sentences_threshold = num_sentences
196
+ if (self._num_sentences_threshold is None or
197
+ self._num_sentences_threshold < 0):
198
+ self._num_sentences_threshold = random.randint(1, _MAX_NUM_SENTENCES)
199
+
200
+ if relation is None:
201
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
202
+ elif relation not in _COMPARISON_RELATION:
203
+ raise ValueError("The supported relation for comparison must be in "
204
+ f"{_COMPARISON_RELATION}, but {relation} is given.")
205
+ else:
206
+ self._comparison_relation = relation
207
+
208
+ self._description_pattern = (
209
+ "Your response should contain {relation} {num_sentences} sentences.")
210
+ return self._description_pattern.format(
211
+ relation=self._comparison_relation,
212
+ num_sentences=self._num_sentences_threshold)
213
+
214
+ def get_instruction_args(self):
215
+ """Returns the keyward args of `build_description`."""
216
+ return {"num_sentences": self._num_sentences_threshold,
217
+ "relation": self._comparison_relation}
218
+
219
+ def get_instruction_args_keys(self):
220
+ """Returns the args keys of `build_description`."""
221
+ return ["num_sentences", "relation"]
222
+
223
+ def check_following(self, value):
224
+ """Check if the number of sentences follows the instruction.
225
+
226
+ Args:
227
+ value: A string representing the response.
228
+
229
+ Returns:
230
+ True if the response follows the instruction.
231
+
232
+ Raise:
233
+ ValueError if the string in `instruction_args` is not in
234
+ [`less_than`, `at_least`].
235
+ """
236
+ num_sentences = instructions_util.count_sentences(value)
237
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
238
+ return num_sentences < self._num_sentences_threshold
239
+ elif self._comparison_relation == _COMPARISON_RELATION[1]:
240
+ return num_sentences >= self._num_sentences_threshold
241
+
242
+
243
+ class PlaceholderChecker(Instruction):
244
+ """Check the placeholders in template writing."""
245
+
246
+ def build_description(self, *, num_placeholders = None):
247
+ """Build the instruction description.
248
+
249
+ Args:
250
+ num_placeholders: An integer denoting the minimum number of
251
+ placeholders required in the response.
252
+
253
+ Returns:
254
+ A string representing the instruction description.
255
+ """
256
+ self._num_placeholders = num_placeholders
257
+ if self._num_placeholders is None or self._num_placeholders < 0:
258
+ self._num_placeholders = random.randint(1, _NUM_PLACEHOLDERS)
259
+ self._description_pattern = (
260
+ "The response must contain at least {num_placeholders} placeholders " +
261
+ "represented by square brackets, such as [address].")
262
+ return self._description_pattern.format(
263
+ num_placeholders=self._num_placeholders)
264
+
265
+ def get_instruction_args(self):
266
+ """Returns the keyward args of `build_description`."""
267
+ return {"num_placeholders": self._num_placeholders}
268
+
269
+ def get_instruction_args_keys(self):
270
+ """Returns the args keys of `build_description`."""
271
+ return ["num_placeholders"]
272
+
273
+ def check_following(self, value):
274
+ """Check if the number of placeholders follows the instruction.
275
+
276
+ Args:
277
+ value: A string representing the response.
278
+
279
+ Returns:
280
+ True if the actual number of placeholders in the response is greater than
281
+ or equal to `num_placeholders`; otherwise, False.
282
+ """
283
+ placeholders = re.findall(r"\[.*?\]", value)
284
+ num_placeholders = len(placeholders)
285
+ return num_placeholders >= self._num_placeholders
286
+
287
+
288
+ class BulletListChecker(Instruction):
289
+ """Checks the bullet list in the prompt."""
290
+
291
+ def build_description(self, *, num_bullets = None):
292
+ """Build the instruction description.
293
+
294
+ Args:
295
+ num_bullets: An integer specifying the exact number of bullet lists
296
+ that is required to appear in the response.
297
+
298
+ Returns:
299
+ A string representing the instruction description.
300
+ """
301
+ self._num_bullets = num_bullets
302
+ if self._num_bullets is None or self._num_bullets < 0:
303
+ self._num_bullets = random.randint(1, _NUM_BULLETS)
304
+ self._description_pattern = (
305
+ "Your answer must contain exactly {num_bullets} bullet points. " +
306
+ "Use the markdown bullet points such as:\n" +
307
+ "* This is point 1. \n" +
308
+ "* This is point 2")
309
+ return self._description_pattern.format(
310
+ num_bullets=self._num_bullets)
311
+
312
+ def get_instruction_args(self):
313
+ """Returns the keyward args of `build_description`."""
314
+ return {"num_bullets": self._num_bullets}
315
+
316
+ def get_instruction_args_keys(self):
317
+ """Returns the args keys of `build_description`."""
318
+ return ["num_bullets"]
319
+
320
+ def check_following(self, value):
321
+ r"""Check if the number of bullet lists meets the requirement.
322
+
323
+ Args:
324
+ value: A string representing the response. The response is expected to
325
+ contain some bullet lists that start with `\*`.
326
+
327
+ Returns:
328
+ True if the actual number of bullet lists in the response meets the
329
+ requirement.
330
+ """
331
+ bullet_lists = re.findall(r"^\s*\*[^\*].*$", value, flags=re.MULTILINE)
332
+ bullet_lists_2 = re.findall(r"^\s*-.*$", value, flags=re.MULTILINE)
333
+ num_bullet_lists = len(bullet_lists) + len(bullet_lists_2)
334
+ return num_bullet_lists == self._num_bullets
335
+
336
+
337
+ class ConstrainedResponseChecker(Instruction):
338
+ """Checks the constrained response."""
339
+
340
+ def build_description(self):
341
+ """Build the instruction description."""
342
+ # A sequence of string(s) representing the options of the expected response.
343
+ self._constrained_responses = _CONSTRAINED_RESPONSE_OPTIONS
344
+ self._description_pattern = (
345
+ "Answer with one of the following options: {response_options}")
346
+ return self._description_pattern.format(
347
+ response_options=self._constrained_responses)
348
+
349
+ def get_instruction_args(self):
350
+ """Returns the keyward args of `build_description`."""
351
+ return None
352
+
353
+ def get_instruction_args_keys(self):
354
+ """Returns the args keys of `build_description`."""
355
+ return []
356
+
357
+ def check_following(self, value):
358
+ """Checks if the response matches the constrained options.
359
+
360
+ Args:
361
+ value: A string representing the response.
362
+
363
+ Returns:
364
+ True if the actual response contains one of the options in the constrained
365
+ responses; otherwise False.
366
+ """
367
+ value = value.strip()
368
+ for constrained_response in self._constrained_responses:
369
+ if constrained_response in value:
370
+ return True
371
+ return False
372
+
373
+
374
+ class ConstrainedStartChecker(Instruction):
375
+ """Checks the response start."""
376
+
377
+ def build_description(self, *, starter = None):
378
+ """Build the instruction description.
379
+
380
+ Args:
381
+ starter: A string representing the keyward that the response should start
382
+ with.
383
+
384
+ Returns:
385
+ A string representing the instruction description.
386
+ """
387
+ self._starter = starter.strip() if isinstance(starter, str) else starter
388
+ if self._starter is None:
389
+ self._starter = random.choice(_STARTER_OPTIONS)
390
+ self._description_pattern = (
391
+ "During the conversation, when it is your turn, " +
392
+ "please always start with {starter}")
393
+ return self._description_pattern.format(starter=self._starter)
394
+
395
+ def get_instruction_args(self):
396
+ """Returns the keyward args of `build_description`."""
397
+ return {"starter": self._starter}
398
+
399
+ def get_instruction_args_keys(self):
400
+ """Returns the args keys of `build_description`."""
401
+ return ["starter"]
402
+
403
+ def check_following(self, value):
404
+ """Checks if the response starts with the constrained keyword or phrase.
405
+
406
+ Args:
407
+ value: A string representing the response.
408
+
409
+ Returns:
410
+ True if the response starts with the given phrase or keyword that is
411
+ contained in `instruction_args`; otherwise, False.
412
+ """
413
+ response_pattern = r"^\s*" + self._starter + r".*$"
414
+ response_with_constrained_start = re.search(response_pattern, value,
415
+ flags=re.MULTILINE)
416
+ return True if response_with_constrained_start else False
417
+
418
+
419
+ class HighlightSectionChecker(Instruction):
420
+ """Checks the highlighted section."""
421
+
422
+ def build_description(self, *, num_highlights = None):
423
+ """Build the instruction description.
424
+
425
+ Args:
426
+ num_highlights: An integer specifying the minimum number of highlighted
427
+ sections.
428
+
429
+ Returns:
430
+ A string representing the instruction description.
431
+ """
432
+ self._num_highlights = num_highlights
433
+ if self._num_highlights is None or self._num_highlights < 0:
434
+ self._num_highlights = random.randint(1, _NUM_HIGHLIGHTED_SECTIONS)
435
+
436
+ self._description_pattern = (
437
+ "Highlight at least {num_highlights} sections in your answer with " +
438
+ "markdown, i.e. *highlighted section*.")
439
+
440
+ return self._description_pattern.format(num_highlights=self._num_highlights)
441
+
442
+ def get_instruction_args(self):
443
+ """Returns the keyward args of `build_description`."""
444
+ return {"num_highlights": self._num_highlights}
445
+
446
+ def get_instruction_args_keys(self):
447
+ """Returns the args keys of `build_description`."""
448
+ return ["num_highlights"]
449
+
450
+ def check_following(self, value):
451
+ """Checks if the number of highlighted sections meets the requirement.
452
+
453
+ Args:
454
+ value: a string repesenting the response. The response is expected to
455
+ contain highlighted sections in the format of *highlighted*.
456
+
457
+ Returns:
458
+ True if the actual number of highlighted sections in the format of
459
+ *highlighed sections* meets the minimum requirement; otherwise False.
460
+ """
461
+ num_highlights = 0
462
+ highlights = re.findall(r"\*[^\n\*]*\*", value)
463
+ double_highlights = re.findall(r"\*\*[^\n\*]*\*\*", value)
464
+ for highlight in highlights:
465
+ if highlight.strip("*").strip():
466
+ num_highlights += 1
467
+ for highlight in double_highlights:
468
+ if highlight.removeprefix("**").removesuffix("**").strip():
469
+ num_highlights += 1
470
+
471
+ return num_highlights >= self._num_highlights
472
+
473
+
474
+ class SectionChecker(Instruction):
475
+ """Checks the sections."""
476
+
477
+ def build_description(self, *, section_spliter = None,
478
+ num_sections = None):
479
+ """Build the instruction description.
480
+
481
+ Args:
482
+ section_spliter: A string represents the section spliter keyword that
483
+ marks a new section, i.e., `Section` or `SECTION`.
484
+ num_sections: An integer specifying the number of sections.
485
+
486
+ Returns:
487
+ A string representing the instruction description.
488
+ """
489
+ self._section_spliter = section_spliter.strip() if isinstance(
490
+ section_spliter, str) else section_spliter
491
+ if self._section_spliter is None:
492
+ self._section_spliter = random.choice(_SECTION_SPLITER)
493
+
494
+ self._num_sections = num_sections
495
+ if self._num_sections is None or self._num_sections < 0:
496
+ self._num_sections = random.randint(1, _NUM_SECTIONS)
497
+
498
+ self._description_pattern = (
499
+ "Your response must have {num_sections} sections. Mark the beginning " +
500
+ "of each section with {section_spliter} X, such as:\n" +
501
+ "{section_spliter} 1\n" +
502
+ "[content of section 1]\n" +
503
+ "{section_spliter} 2\n" +
504
+ "[content of section 2]")
505
+
506
+ return self._description_pattern.format(
507
+ num_sections=self._num_sections,
508
+ section_spliter=self._section_spliter)
509
+
510
+ def get_instruction_args(self):
511
+ """Returns the keyward args of `build_description`."""
512
+ return {"section_spliter": self._section_spliter,
513
+ "num_sections": self._num_sections}
514
+
515
+ def get_instruction_args_keys(self):
516
+ """Returns the args keys of `build_description`."""
517
+ return ["section_spliter", "num_sections"]
518
+
519
+ def check_following(self, value):
520
+ """Checks the response contains multiple sections.
521
+
522
+ Args:
523
+ value: A string representing the response. The response is expected
524
+ to contain multiple sections (number of sections is greater than 1).
525
+ A new section starts with `Section 1`, where the number denotes the
526
+ section index.
527
+
528
+ Returns:
529
+ True if the number of sections in the response is greater than or equal to
530
+ the minimum number of sections; otherwise, False.
531
+ """
532
+ section_splitter_patten = r"\s?" + self._section_spliter + r"\s?\d+\s?"
533
+ sections = re.split(section_splitter_patten, value)
534
+ num_sections = len(sections) - 1
535
+ return num_sections >= self._num_sections
536
+
537
+
538
+ class ParagraphChecker(Instruction):
539
+ """Checks the paragraphs."""
540
+
541
+ def build_description(self, *, num_paragraphs = None):
542
+ """Build the instruction description.
543
+
544
+ Args:
545
+ num_paragraphs: An integer specifying the number of paragraphs.
546
+
547
+ Returns:
548
+ A string representing the instruction description.
549
+ """
550
+ self._num_paragraphs = num_paragraphs
551
+ if self._num_paragraphs is None or self._num_paragraphs < 0:
552
+ self._num_paragraphs = random.randint(1, _NUM_PARAGRAPHS)
553
+
554
+ self._description_pattern = (
555
+ "There should be {num_paragraphs} paragraphs. " +
556
+ "Paragraphs are separated with the markdown divider: ***")
557
+
558
+ return self._description_pattern.format(num_paragraphs=self._num_paragraphs)
559
+
560
+ def get_instruction_args(self):
561
+ """Returns the keyward args of `build_description`."""
562
+ return {"num_paragraphs": self._num_paragraphs}
563
+
564
+ def get_instruction_args_keys(self):
565
+ """Returns the args keys of `build_description`."""
566
+ return ["num_paragraphs"]
567
+
568
+ def check_following(self, value):
569
+ """Checks the response contains required number of paragraphs.
570
+
571
+ Args:
572
+ value: A string representing the response. The response may contain
573
+ paragraphs that are separated by the markdown divider: `***`.
574
+
575
+ Returns:
576
+ True if the actual number of paragraphs is the same as required;
577
+ otherwise, False.
578
+ """
579
+ paragraphs = re.split(r"\s?\*\*\*\s?", value)
580
+ num_paragraphs = len(paragraphs)
581
+
582
+ for index, paragraph in enumerate(paragraphs):
583
+ if not paragraph.strip():
584
+ if index == 0 or index == len(paragraphs) - 1:
585
+ num_paragraphs -= 1
586
+ else:
587
+ return False
588
+
589
+ return num_paragraphs == self._num_paragraphs
590
+
591
+
592
+ class PostscriptChecker(Instruction):
593
+ """Checks the postscript."""
594
+
595
+ def build_description(self, *, postscript_marker = None
596
+ ):
597
+ """Build the instruction description.
598
+
599
+ Args:
600
+ postscript_marker: A string containing the keyword that marks the start
601
+ of the postscript section.
602
+
603
+ Returns:
604
+ A string representing the instruction description.
605
+ """
606
+ self._postscript_marker = postscript_marker.strip() if isinstance(
607
+ postscript_marker, str) else postscript_marker
608
+ if self._postscript_marker is None:
609
+ self._postscript_marker = random.choice(_POSTSCRIPT_MARKER)
610
+
611
+ self._description_pattern = (
612
+ "At the end of your response, please explicitly add a postscript " +
613
+ "starting with {postscript}")
614
+
615
+ return self._description_pattern.format(postscript=self._postscript_marker)
616
+
617
+ def get_instruction_args(self):
618
+ """Returns the keyward args of `build_description`."""
619
+ return {"postscript_marker": self._postscript_marker}
620
+
621
+ def get_instruction_args_keys(self):
622
+ """Returns the args keys of `build_description`."""
623
+ return ["postscript_marker"]
624
+
625
+ def check_following(self, value):
626
+ """Checks if the response follows the postscript format.
627
+
628
+ Args:
629
+ value: a string representing the response. The response is expected to
630
+ contain a postscript section.
631
+
632
+ Returns:
633
+ True if the response contains a postscript section starting with
634
+ the keyword containing in the `instruction_args`; otherwise False.
635
+ """
636
+ value = value.lower()
637
+ if self._postscript_marker == "P.P.S":
638
+ postscript_pattern = r"\s*p\.\s?p\.\s?s.*$"
639
+ elif self._postscript_marker == "P.S.":
640
+ postscript_pattern = r"\s*p\.\s?s\..*$"
641
+ else:
642
+ postscript_pattern = r"\s*" + self._postscript_marker.lower() + r".*$"
643
+ postscript = re.findall(postscript_pattern, value, flags=re.MULTILINE)
644
+ return True if postscript else False
645
+
646
+
647
+ class RephraseChecker(Instruction):
648
+ """Checks the repharse."""
649
+
650
+ def build_description(self, *, original_message):
651
+ """Build the instruction description.
652
+
653
+ Args:
654
+ original_message: A string representing the original message. The
655
+ rephrased response should only change its words/sentences in between
656
+ its two asterisks, for example, *change me*. Both original and rephrased
657
+ messages should contain the changes in the form of *change me*.
658
+
659
+ Returns:
660
+ A string representing the instruction description.
661
+ """
662
+ if not self.is_change(original_message):
663
+ raise ValueError(f"Message {original_message} does not contain changes "
664
+ "in the form of *change me*.")
665
+
666
+ self._reference_without_change = original_message
667
+ self._description = ("Rephrasing: Your rephrased response should only" +
668
+ "change the words/sentences in between two asterisks" +
669
+ "such as *change me*.")
670
+ return self._description
671
+
672
+ def get_instruction_args(self):
673
+ """Returns the keyward args of `build_description`."""
674
+ return {"original_message": self._reference_without_change}
675
+
676
+ def get_instruction_args_keys(self):
677
+ """Returns the args keys of `build_description`."""
678
+ return ["original_message"]
679
+
680
+ def check_following(self, value):
681
+ r"""Checks if the rephrasing follows the instruction.
682
+
683
+ Args:
684
+ value: A string representing the response, which is expected to rephras
685
+ the string of `instruction_args`.
686
+
687
+ Returns:
688
+ True if `value` and `instruction_args` only differ by the words/sentences
689
+ in between two asterisks such as *change me*; otherwise, False.
690
+ """
691
+
692
+ if not self.is_change(value):
693
+ raise ValueError(f"value {value} does not contain "
694
+ "changes in the form of *change me*.")
695
+
696
+ response_without_changes = self.strip_changes(value)
697
+ reference_without_changes = self.strip_changes(
698
+ self._reference_without_change)
699
+
700
+ return response_without_changes == reference_without_changes
701
+
702
+ def is_change(self, response):
703
+ """Check if there is change in the response in the form of *change me*."""
704
+ return re.search(r"\*.*\*", response)
705
+
706
+ def strip_changes(self, response):
707
+ """Strips off the changes."""
708
+ return re.sub(r"\*.*\*", "", response)
709
+
710
+
711
+ class KeywordChecker(Instruction):
712
+ """Check the exisitence of certain keywords."""
713
+
714
+ def build_description(self, *, keywords = None
715
+ ):
716
+ """Build the instruction description.
717
+
718
+ Args:
719
+ keywords: A sequence of strings representing the keywords that are
720
+ expected in the response.
721
+
722
+ Returns:
723
+ A string representing the instruction description.
724
+ """
725
+
726
+ if not keywords:
727
+ self._keywords = instructions_util.generate_keywords(
728
+ num_keywords=_NUM_KEYWORDS)
729
+ else:
730
+ self._keywords = keywords
731
+ self._keywords = sorted(self._keywords)
732
+
733
+ self._description_pattern = ("Include keywords {keywords} in the response.")
734
+
735
+ return self._description_pattern.format(keywords=self._keywords)
736
+
737
+ def get_instruction_args(self):
738
+ """Returns the keyward args of `build_description`."""
739
+ return {"keywords": self._keywords}
740
+
741
+ def get_instruction_args_keys(self):
742
+ """Returns the args keys of `build_description`."""
743
+ return ["keywords"]
744
+
745
+ def check_following(self, value):
746
+ """Check if the response contain the expected keywords."""
747
+ for keyword in self._keywords:
748
+ if not re.search(keyword, value, flags=re.IGNORECASE):
749
+ return False
750
+ return True
751
+
752
+
753
+ class KeywordFrequencyChecker(Instruction):
754
+ """Check the keyword frequency."""
755
+
756
+ def build_description(self, *, keyword = None,
757
+ frequency = None,
758
+ relation = None):
759
+ """Build the instruction description.
760
+
761
+ Args:
762
+ keyword: A string representing a keyword that is expected in the response.
763
+ frequency: An integer specifying the number of times `keyword` is expected
764
+ to appear in the response.
765
+ relation: A string in (`less than`, `at least`), defining the relational
766
+ operator for comparison.
767
+ Two relational comparisons are supported for now:
768
+ if 'less than', the actual number of occurrences < frequency;
769
+ if 'at least', the actual number of occurrences >= frequency.
770
+
771
+ Returns:
772
+ A string representing the instruction description.
773
+ """
774
+ if not keyword:
775
+ self._keyword = instructions_util.generate_keywords(num_keywords=1)[0]
776
+ else:
777
+ self._keyword = keyword.strip()
778
+
779
+ self._frequency = frequency
780
+ if self._frequency is None or self._frequency < 0:
781
+ self._frequency = random.randint(1, _KEYWORD_FREQUENCY)
782
+
783
+ if relation is None:
784
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
785
+ elif relation not in _COMPARISON_RELATION:
786
+ raise ValueError("The supported relation for comparison must be in "
787
+ f"{_COMPARISON_RELATION}, but {relation} is given.")
788
+ else:
789
+ self._comparison_relation = relation
790
+
791
+ self._description_pattern = (
792
+ "In your response, the word {keyword} should appear {relation} " +
793
+ "{frequency} times.")
794
+
795
+ return self._description_pattern.format(
796
+ keyword=self._keyword,
797
+ relation=self._comparison_relation,
798
+ frequency=self._frequency)
799
+
800
+ def get_instruction_args(self):
801
+ """Returns the keyward args of `build_description`."""
802
+ return {"keyword": self._keyword,
803
+ "frequency": self._frequency,
804
+ "relation": self._comparison_relation}
805
+
806
+ def get_instruction_args_keys(self):
807
+ """Returns the args keys of `build_description`."""
808
+ return ["keyword", "frequency", "relation"]
809
+
810
+ def check_following(self, value):
811
+ """Checks if the response contain the keyword with required frequency."""
812
+ actual_occurrences = len(re.findall(
813
+ self._keyword, value, flags=re.IGNORECASE))
814
+
815
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
816
+ return actual_occurrences < self._frequency
817
+ elif self._comparison_relation == _COMPARISON_RELATION[1]:
818
+ return actual_occurrences >= self._frequency
819
+
820
+
821
+ class NumberOfWords(Instruction):
822
+ """Checks the number of words."""
823
+
824
+ def build_description(self, *, num_words = None,
825
+ relation = None):
826
+ """Build the instruction description.
827
+
828
+ Args:
829
+ num_words: An integer specifying the number of words contained in the
830
+ response.
831
+ relation: A string in (`less than`, `at least`), defining the relational
832
+ operator for comparison.
833
+ Two relational comparisons are supported for now:
834
+ if 'less than', the actual number of words < num_words;
835
+ if 'at least', the actual number of words >= num_words.
836
+
837
+ Returns:
838
+ A string representing the instruction description.
839
+ """
840
+
841
+ self._num_words = num_words
842
+ if self._num_words is None or self._num_words < 0:
843
+ self._num_words = random.randint(
844
+ _NUM_WORDS_LOWER_LIMIT, _NUM_WORDS_UPPER_LIMIT
845
+ )
846
+
847
+ if relation is None:
848
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
849
+ elif relation not in _COMPARISON_RELATION:
850
+ raise ValueError("The supported relation for comparison must be in "
851
+ f"{_COMPARISON_RELATION}, but {relation} is given.")
852
+ else:
853
+ self._comparison_relation = relation
854
+
855
+ self._description_pattern = (
856
+ "Answer with {relation} {num_words} words.")
857
+
858
+ return self._description_pattern.format(
859
+ relation=self._comparison_relation,
860
+ num_words=self._num_words)
861
+
862
+ def get_instruction_args(self):
863
+ """Returns the keyward args of `build_description`."""
864
+ return {"num_words": self._num_words,
865
+ "relation": self._comparison_relation}
866
+
867
+ def get_instruction_args_keys(self):
868
+ """Returns the args keys of `build_description`."""
869
+ return ["num_words", "relation"]
870
+
871
+ def check_following(self, value):
872
+ """Checks if the response contains the expected number of words."""
873
+ num_words = instructions_util.count_words(value)
874
+
875
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
876
+ return num_words < self._num_words
877
+ elif self._comparison_relation == _COMPARISON_RELATION[1]:
878
+ return num_words >= self._num_words
879
+
880
+
881
+ class JsonFormat(Instruction):
882
+ """Check the Json format."""
883
+
884
+ def build_description(self):
885
+ self._description_pattern = (
886
+ "Entire output should be wrapped in JSON format. You can use markdown"
887
+ " ticks such as ```."
888
+ )
889
+ return self._description_pattern
890
+
891
+ def get_instruction_args(self):
892
+ """Returns the keyward args of `build_description`."""
893
+ return None
894
+
895
+ def get_instruction_args_keys(self):
896
+ """Returns the args keys of `build_description`."""
897
+ return []
898
+
899
+ def check_following(self, value):
900
+ value = (
901
+ value.strip()
902
+ .removeprefix("```json")
903
+ .removeprefix("```Json")
904
+ .removeprefix("```JSON")
905
+ .removeprefix("```")
906
+ .removesuffix("```")
907
+ .strip()
908
+ )
909
+ try:
910
+ json.loads(value)
911
+ except ValueError as _:
912
+ return False
913
+ return True
914
+
915
+
916
+ class ParagraphFirstWordCheck(Instruction):
917
+ """Check the paragraph and the first word of the nth paragraph."""
918
+
919
+ def build_description(self, num_paragraphs = None,
920
+ nth_paragraph = None,
921
+ first_word = None):
922
+ r"""Build the instruction description.
923
+
924
+ Args:
925
+ num_paragraphs: An integer indicating the number of paragraphs expected
926
+ in the response. A paragraph is a subset of the string that is
927
+ expected to be separated by '\n\n'.
928
+ nth_paragraph: An integer indicating the paragraph number that we look at.
929
+ Note that n starts from 1.
930
+ first_word: A string that represent the first word of the bth paragraph.
931
+
932
+ Returns:
933
+ A string representing the instruction description.
934
+ """
935
+ self._num_paragraphs = num_paragraphs
936
+ if self._num_paragraphs is None or self._num_paragraphs < 0:
937
+ self._num_paragraphs = random.randint(1, _NUM_PARAGRAPHS)
938
+
939
+ self._nth_paragraph = nth_paragraph
940
+ if (
941
+ self._nth_paragraph is None
942
+ or self._nth_paragraph <= 0
943
+ or self._nth_paragraph > self._num_paragraphs
944
+ ):
945
+ self._nth_paragraph = random.randint(1, self._num_paragraphs + 1)
946
+
947
+ self._first_word = first_word
948
+ if self._first_word is None:
949
+ self._first_word = instructions_util.generate_keywords(num_keywords=1)[0]
950
+ self._first_word = self._first_word.lower()
951
+
952
+ self._description_pattern = (
953
+ "There should be {num_paragraphs} paragraphs. " +
954
+ "Paragraphs and only paragraphs are separated with each other by two " +
955
+ "new lines as if it was '\\n\\n' in python. " +
956
+ "Paragraph {nth_paragraph} must start with word {first_word}.")
957
+
958
+ return self._description_pattern.format(
959
+ num_paragraphs=self._num_paragraphs,
960
+ nth_paragraph=self._nth_paragraph,
961
+ first_word=self._first_word)
962
+
963
+ def get_instruction_args(self):
964
+ """Returns the keyward args of `build_description`."""
965
+ return {"num_paragraphs": self._num_paragraphs,
966
+ "nth_paragraph": self._nth_paragraph,
967
+ "first_word": self._first_word}
968
+
969
+ def get_instruction_args_keys(self):
970
+ """Returns the args keys of `build_description`."""
971
+ return ["num_paragraphs", "nth_paragraph", "first_word"]
972
+
973
+ def check_following(self, value):
974
+ """Checks for required number of paragraphs and correct first word.
975
+
976
+ Args:
977
+ value: a string representing the response. The response may contain
978
+ paragraphs that are separated by two new lines and the first word of
979
+ the nth paragraph will have to match a specified word.
980
+
981
+ Returns:
982
+ True if the number of paragraphs is the same as required and the first
983
+ word of the specified paragraph is the same as required. Otherwise, false.
984
+ """
985
+
986
+ paragraphs = re.split(r"\n\n", value)
987
+ num_paragraphs = len(paragraphs)
988
+
989
+ for paragraph in paragraphs:
990
+ if not paragraph.strip():
991
+ num_paragraphs -= 1
992
+
993
+ # check that index doesn't go out of bounds
994
+ if self._nth_paragraph <= num_paragraphs:
995
+ paragraph = paragraphs[self._nth_paragraph - 1].strip()
996
+ if not paragraph:
997
+ return False
998
+ else:
999
+ return False
1000
+
1001
+ first_word = ""
1002
+ punctuation = {".", ",", "?", "!", "'", '"'}
1003
+
1004
+ # get first word and remove punctuation
1005
+ word = paragraph.split()[0].strip()
1006
+ # TODO(jeffrey): make more complex?
1007
+ word = word.lstrip("'")
1008
+ word = word.lstrip('"')
1009
+
1010
+ for letter in word:
1011
+ if letter in punctuation:
1012
+ break
1013
+ first_word += letter.lower()
1014
+
1015
+ return (
1016
+ num_paragraphs == self._num_paragraphs
1017
+ and first_word == self._first_word
1018
+ )
1019
+
1020
+
1021
+ # TODO(jeffrey) add relation - at least/at most?
1022
+ class KeySentenceChecker(Instruction):
1023
+ """Check the existence of certain key sentences."""
1024
+
1025
+ def build_description(self, key_sentences = None,
1026
+ num_sentences = None):
1027
+ """Build the instruction description.
1028
+
1029
+ Args:
1030
+ key_sentences: A sequences of strings representing the key sentences that
1031
+ are expected in the response.
1032
+ num_sentences: The number of key sentences that are expected to be seen in
1033
+ the response.
1034
+
1035
+ Returns:
1036
+ A string representing the instruction description.
1037
+ """
1038
+
1039
+ if not key_sentences:
1040
+ # TODO(jeffrey) make a generate sentences function? wonderwords package
1041
+ self._key_sentences = set(["For now, this is fine."])
1042
+ else:
1043
+ self._key_sentences = key_sentences
1044
+
1045
+ if not num_sentences:
1046
+ self._num_sentences = random.randint(1, len(self._key_sentences))
1047
+ else:
1048
+ self._num_sentences = num_sentences
1049
+
1050
+ self._description_pattern = (
1051
+ "Include {num_sentences} of the following sentences {key_sentences}"
1052
+ )
1053
+
1054
+ return self._description_pattern.format(
1055
+ num_sentences=self._num_sentences, key_sentences=self._key_sentences
1056
+ )
1057
+
1058
+ def get_instruction_args(self):
1059
+ """Returns the keyward args of `build_description`."""
1060
+ return {"num_sentences": self._num_sentences,
1061
+ "key_sentences": list(self._key_sentences)}
1062
+
1063
+ def get_instruction_args_keys(self):
1064
+ """Returns the args keys of `build_description`."""
1065
+ return ["num_sentences", "key_sentences"]
1066
+
1067
+ def check_following(self, value):
1068
+ """Checks if the response contains the expected key sentences."""
1069
+ count = 0
1070
+ sentences = instructions_util.split_into_sentences(value)
1071
+ for sentence in self._key_sentences:
1072
+ if sentence in sentences:
1073
+ count += 1
1074
+
1075
+ return count == self._num_sentences
1076
+
1077
+
1078
+ class ForbiddenWords(Instruction):
1079
+ """Checks that specified words are not used in response."""
1080
+
1081
+ def build_description(self, forbidden_words = None
1082
+ ):
1083
+ """Build the instruction description.
1084
+
1085
+ Args:
1086
+ forbidden_words: A sequences of strings respresenting words that are not
1087
+ allowed in the response.
1088
+
1089
+ Returns:
1090
+ A string representing the instruction description.
1091
+ """
1092
+
1093
+ if not forbidden_words:
1094
+ self._forbidden_words = instructions_util.generate_keywords(
1095
+ num_keywords=_NUM_KEYWORDS)
1096
+ else:
1097
+ self._forbidden_words = list(set(forbidden_words))
1098
+ self._forbidden_words = sorted(self._forbidden_words)
1099
+ self._description_pattern = (
1100
+ "Do not include keywords {forbidden_words} in the response."
1101
+ )
1102
+
1103
+ return self._description_pattern.format(
1104
+ forbidden_words=self._forbidden_words
1105
+ )
1106
+
1107
+ def get_instruction_args(self):
1108
+ """Returns the keyward args of `build_description`."""
1109
+ return {"forbidden_words": self._forbidden_words}
1110
+
1111
+ def get_instruction_args_keys(self):
1112
+ """Returns the args keys of `build_description`."""
1113
+ return ["forbidden_words"]
1114
+
1115
+ def check_following(self, value):
1116
+ """Check if the response does not contain the expected keywords."""
1117
+ for word in self._forbidden_words:
1118
+ if re.search(r"\b" + word + r"\b", value, flags=re.IGNORECASE):
1119
+ return False
1120
+ return True
1121
+
1122
+
1123
+ class RephraseParagraph(Instruction):
1124
+ """Checks that the paragraph is rephrased."""
1125
+
1126
+ def build_description(self, *, original_paragraph, low, high
1127
+ ):
1128
+ """Builds the instruction description.
1129
+
1130
+ Args:
1131
+ original_paragraph: A string presenting the original paragraph. The
1132
+ rephrases response should have betweeb low-high words in common.
1133
+ low: An integer presenting the lower bound of similar words.
1134
+ high: An integer representing the upper bound of similar words.
1135
+
1136
+ Returns:
1137
+ A string representing the instruction description.
1138
+ """
1139
+ # TODO(jeffrey) make more encompassing
1140
+ self._original_paragraph = original_paragraph
1141
+ self._low = low
1142
+ self._high = high
1143
+
1144
+ self._description = ("Rephrase the following paragraph: " +
1145
+ "{original_paragraph}\nYour response should have " +
1146
+ "between {low} and {high} of the same words. " +
1147
+ "Words are the same if and only if all of the " +
1148
+ "letters, ignoring cases, are the same. For " +
1149
+ "example, 'run' is the same as 'Run' but different " +
1150
+ "to 'ran'.")
1151
+
1152
+ return self._description.format(original_paragraph=original_paragraph,
1153
+ low=self._low, high=self._high)
1154
+
1155
+ def get_instruction_args(self):
1156
+ """Returns the keyward args of `build_description`."""
1157
+ return {"original_paragraph": self._original_paragraph,
1158
+ "low": self._low,
1159
+ "high": self._high}
1160
+
1161
+ def get_instruction_args_keys(self):
1162
+ """Returns the args keys of `build_description`."""
1163
+ return ["original_paragraph", "low", "high"]
1164
+
1165
+ def check_following(self, value):
1166
+ val_words = re.findall(r"\w+", value.lower())
1167
+ original_words = re.findall(r"\w+", self._original_paragraph.lower())
1168
+ similar_words = 0
1169
+
1170
+ dict_val = collections.Counter(val_words)
1171
+ dict_original = collections.Counter(original_words)
1172
+
1173
+ for word in dict_original:
1174
+ similar_words += min(dict_original[word], dict_val[word])
1175
+
1176
+ return similar_words >= self._low and similar_words <= self._high
1177
+
1178
+
1179
+ class TwoResponsesChecker(Instruction):
1180
+ """Check that two responses were given."""
1181
+
1182
+ def build_description(self):
1183
+ """Build the instruction description."""
1184
+ self._description_pattern = (
1185
+ "Give two different responses. Responses and only responses should"
1186
+ " be separated by 6 asterisk symbols: ******."
1187
+ )
1188
+ return self._description_pattern
1189
+
1190
+ def get_instruction_args(self):
1191
+ """Returns the keyward args of `build_description`."""
1192
+ return None
1193
+
1194
+ def get_instruction_args_keys(self):
1195
+ """Returns the args keys of `build_description`."""
1196
+ return []
1197
+
1198
+ def check_following(self, value):
1199
+ """Checks if the response has two different answers.
1200
+
1201
+ Args:
1202
+ value: A string representing the response.
1203
+
1204
+ Returns:
1205
+ True if two responses are detected and false otherwise.
1206
+ """
1207
+ valid_responses = list()
1208
+ responses = value.split("******")
1209
+ for index, response in enumerate(responses):
1210
+ if not response.strip():
1211
+ if index != 0 and index != len(responses) - 1:
1212
+ return False
1213
+ else:
1214
+ valid_responses.append(response)
1215
+ return (
1216
+ len(valid_responses) == 2
1217
+ and valid_responses[0].strip() != valid_responses[1].strip()
1218
+ )
1219
+
1220
+
1221
+ class RepeatPromptThenAnswer(Instruction):
1222
+ """Checks that Prompt is first repeated then answered."""
1223
+
1224
+ def build_description(self, *, prompt_to_repeat = None):
1225
+ """Build the instruction description.
1226
+
1227
+ Args:
1228
+ prompt_to_repeat: The prompt that is meant to be repeated.
1229
+
1230
+ Returns:
1231
+ A string representing the instruction description.
1232
+ """
1233
+ if not prompt_to_repeat:
1234
+ raise ValueError("prompt_to_repeat must be set.")
1235
+ else:
1236
+ self._prompt_to_repeat = prompt_to_repeat
1237
+ self._description_pattern = (
1238
+ "First repeat the request word for word without change,"
1239
+ " then give your answer (1. do not say any words or characters"
1240
+ " before repeating the request; 2. the request you need to repeat"
1241
+ " does not include this sentence)"
1242
+ )
1243
+ return self._description_pattern
1244
+
1245
+ def get_instruction_args(self):
1246
+ return {"prompt_to_repeat": self._prompt_to_repeat}
1247
+
1248
+ def get_instruction_args_keys(self):
1249
+ """Returns the args keys of `build_description`."""
1250
+ return ["prompt_to_repeat"]
1251
+
1252
+ def check_following(self, value):
1253
+ if value.strip().lower().startswith(self._prompt_to_repeat.strip().lower()):
1254
+ return True
1255
+ return False
1256
+
1257
+
1258
+ class EndChecker(Instruction):
1259
+ """Checks that the prompt ends with a given phrase."""
1260
+
1261
+ def build_description(self, *, end_phrase = None):
1262
+ """Build the instruction description.
1263
+
1264
+ Args:
1265
+ end_phrase: A string representing the phrase the response should end with.
1266
+
1267
+ Returns:
1268
+ A string representing the instruction description.
1269
+ """
1270
+ self._end_phrase = (
1271
+ end_phrase.strip() if isinstance(end_phrase, str) else end_phrase
1272
+ )
1273
+ if self._end_phrase is None:
1274
+ self._end_phrase = random.choice(_ENDING_OPTIONS)
1275
+ self._description_pattern = (
1276
+ "Finish your response with this exact phrase {ender}. "
1277
+ "No other words should follow this phrase.")
1278
+ return self._description_pattern.format(ender=self._end_phrase)
1279
+
1280
+ def get_instruction_args(self):
1281
+ return {"end_phrase": self._end_phrase}
1282
+
1283
+ def get_instruction_args_keys(self):
1284
+ """Returns the args keys of `build_description`."""
1285
+ return ["end_phrase"]
1286
+
1287
+ def check_following(self, value):
1288
+ """Checks if the response ends with the expected phrase."""
1289
+ value = value.strip().strip("\"").lower()
1290
+ self._end_phrase = self._end_phrase.strip().lower()
1291
+ return value.endswith(self._end_phrase)
1292
+
1293
+
1294
+ class TitleChecker(Instruction):
1295
+ """Checks the response for a title."""
1296
+
1297
+ def build_description(self):
1298
+ """Build the instruction description."""
1299
+ self._description_pattern = (
1300
+ "Your answer must contain a title, wrapped in double angular brackets,"
1301
+ " such as <<poem of joy>>."
1302
+ )
1303
+ return self._description_pattern
1304
+
1305
+ def get_instruction_args(self):
1306
+ return None
1307
+
1308
+ def get_instruction_args_keys(self):
1309
+ """Returns the args keys of `build_description`."""
1310
+ return []
1311
+
1312
+ def check_following(self, value):
1313
+ """Checks if the response contains a title."""
1314
+ pattern = r"<<[^\n]+>>"
1315
+ re_pattern = re.compile(pattern)
1316
+ titles = re.findall(re_pattern, value)
1317
+
1318
+ for title in titles:
1319
+ if title.lstrip("<").rstrip(">").strip():
1320
+ return True
1321
+ return False
1322
+
1323
+
1324
+ class LetterFrequencyChecker(Instruction):
1325
+ """Checks letter frequency."""
1326
+
1327
+ def build_description(self, *, letter = None,
1328
+ let_frequency = None,
1329
+ let_relation = None):
1330
+ """Build the instruction description.
1331
+
1332
+ Args:
1333
+ letter: A string representing a letter that is expected in the response.
1334
+ let_frequency: An integer specifying the number of times `keyword` is
1335
+ expected to appear in the response.
1336
+ let_relation: A string in (`less than`, `at least`), defining the
1337
+ relational operator for comparison. Two relational comparisons are
1338
+ supported for now; if 'less than', the actual number of
1339
+ occurrences < frequency; if 'at least', the actual number of
1340
+ occurrences >= frequency.
1341
+
1342
+ Returns:
1343
+ A string representing the instruction description.
1344
+ """
1345
+ if (
1346
+ not letter
1347
+ or len(letter) > 1
1348
+ or ord(letter.lower()) < 97
1349
+ or ord(letter.lower()) > 122
1350
+ ):
1351
+ self._letter = random.choice(list(string.ascii_letters))
1352
+ else:
1353
+ self._letter = letter.strip()
1354
+ self._letter = self._letter.lower()
1355
+
1356
+ self._frequency = let_frequency
1357
+ if self._frequency is None or self._frequency < 0:
1358
+ self._frequency = random.randint(1, _LETTER_FREQUENCY)
1359
+
1360
+ if let_relation is None:
1361
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
1362
+ elif let_relation not in _COMPARISON_RELATION:
1363
+ raise ValueError(
1364
+ "The supported relation for comparison must be in "
1365
+ f"{_COMPARISON_RELATION}, but {let_relation} is given."
1366
+ )
1367
+ else:
1368
+ self._comparison_relation = let_relation
1369
+
1370
+ self._description_pattern = (
1371
+ "In your response, the letter {letter} should appear {let_relation}"
1372
+ " {let_frequency} times."
1373
+ )
1374
+
1375
+ return self._description_pattern.format(
1376
+ letter=self._letter,
1377
+ let_frequency=self._frequency,
1378
+ let_relation=self._comparison_relation,
1379
+ )
1380
+
1381
+ def get_instruction_args(self):
1382
+ """Returns the keyword args of build description."""
1383
+ return {"letter": self._letter,
1384
+ "let_frequency": self._frequency,
1385
+ "let_relation": self._comparison_relation}
1386
+
1387
+ def get_instruction_args_keys(self):
1388
+ """Returns the args keys of `build_description`."""
1389
+ return ["letter", "let_frequency", "let_relation"]
1390
+
1391
+ def check_following(self, value):
1392
+ """Checks that the response contains the letter at the right frequency."""
1393
+ value = value.lower()
1394
+ letters = collections.Counter(value)
1395
+
1396
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
1397
+ return letters[self._letter] < self._frequency
1398
+ else:
1399
+ return letters[self._letter] >= self._frequency
1400
+
1401
+
1402
+ class CapitalLettersEnglishChecker(Instruction):
1403
+ """Checks that the response is in english and is in all capital letters."""
1404
+
1405
+ def build_description(self):
1406
+ """Build the instruction description."""
1407
+ self._description_pattern = (
1408
+ "Your entire response should be in English, and in all capital letters."
1409
+ )
1410
+ return self._description_pattern
1411
+
1412
+ def get_instruction_args(self):
1413
+ return None
1414
+
1415
+ def get_instruction_args_keys(self):
1416
+ """Returns the args keys of `build_description`."""
1417
+ return []
1418
+
1419
+ def check_following(self, value):
1420
+ """Checks that the response is in English and in all capital letters."""
1421
+ assert isinstance(value, str)
1422
+
1423
+ try:
1424
+ return value.isupper() and langdetect.detect(value) == "en"
1425
+ except langdetect.LangDetectException as e:
1426
+ # Count as instruction is followed.
1427
+ logging.error(
1428
+ "Unable to detect language for text %s due to %s", value, e
1429
+ ) # refex: disable=pytotw.037
1430
+ return True
1431
+
1432
+
1433
+ class LowercaseLettersEnglishChecker(Instruction):
1434
+ """Checks that the response is in english and is in all lowercase letters."""
1435
+
1436
+ def build_description(self):
1437
+ """Build the instruction description."""
1438
+ self._description_pattern = (
1439
+ "Your entire response should be in English, and in all lowercase"
1440
+ " letters. No capital letters are allowed."
1441
+ )
1442
+ return self._description_pattern
1443
+
1444
+ def get_instruction_args(self):
1445
+ return None
1446
+
1447
+ def get_instruction_args_keys(self):
1448
+ """Returns the args keys of `build_description`."""
1449
+ return []
1450
+
1451
+ def check_following(self, value):
1452
+ """Checks that the response is in English and in all lowercase letters."""
1453
+ assert isinstance(value, str)
1454
+
1455
+ try:
1456
+ return value.islower() and langdetect.detect(value) == "en"
1457
+ except langdetect.LangDetectException as e:
1458
+ # Count as instruction is followed.
1459
+ logging.error(
1460
+ "Unable to detect language for text %s due to %s", value, e
1461
+ ) # refex: disable=pytotw.037
1462
+ return True
1463
+
1464
+
1465
+ class CommaChecker(Instruction):
1466
+ """Checks the response for no commas."""
1467
+
1468
+ def build_description(self):
1469
+ """Build the instruction description."""
1470
+ self._description_pattern = (
1471
+ "In your entire response, refrain from the use of any commas."
1472
+ )
1473
+ return self._description_pattern
1474
+
1475
+ def get_instruction_args(self):
1476
+ return None
1477
+
1478
+ def get_instruction_args_keys(self):
1479
+ """Returns the args keys of `build_description`."""
1480
+ return []
1481
+
1482
+ def check_following(self, value):
1483
+ """Checks that the response does not contain commas."""
1484
+ return not re.search(r"\,", value)
1485
+
1486
+
1487
+ class CapitalWordFrequencyChecker(Instruction):
1488
+ """Checks frequency of words with all capital letters."""
1489
+
1490
+ def build_description(
1491
+ self,
1492
+ capital_frequency = None,
1493
+ capital_relation = None,
1494
+ ):
1495
+ """Build the instruction description.
1496
+
1497
+ Args:
1498
+ capital_frequency: An integer that represents the number of words that
1499
+ should be in all capital letters.
1500
+ capital_relation: A string that is 'at least' or 'at most' that refers to
1501
+ the frequency.
1502
+
1503
+ Returns:
1504
+ A string representing the instruction description.
1505
+ """
1506
+ self._frequency = capital_frequency
1507
+ if self._frequency is None:
1508
+ self._frequency = random.randint(1, _ALL_CAPITAL_WORD_FREQUENCY)
1509
+
1510
+ self._comparison_relation = capital_relation
1511
+ if capital_relation is None:
1512
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
1513
+ elif capital_relation not in _COMPARISON_RELATION:
1514
+ raise ValueError(
1515
+ "The supported relation for comparison must be in "
1516
+ f"{_COMPARISON_RELATION}, but {capital_relation} is given."
1517
+ )
1518
+
1519
+ self._description_pattern = (
1520
+ "In your response, words with all capital letters should appear"
1521
+ " {relation} {frequency} times."
1522
+ )
1523
+
1524
+ return self._description_pattern.format(
1525
+ frequency=self._frequency, relation=self._comparison_relation
1526
+ )
1527
+
1528
+ def get_instruction_args(self):
1529
+ """Returns the keyword args of build description."""
1530
+ return {
1531
+ "capital_frequency": self._frequency,
1532
+ "capital_relation": self._comparison_relation,
1533
+ }
1534
+
1535
+ def get_instruction_args_keys(self):
1536
+ """Returns the args keys of `build_description`."""
1537
+ return ["capital_frequency", "capital_relation"]
1538
+
1539
+ def check_following(self, value):
1540
+ """Checks the frequency of words with all capital letters."""
1541
+ # Hyphenated words will count as one word
1542
+ words = instructions_util.nltk.word_tokenize(value)
1543
+ capital_words = [word for word in words if word.isupper()]
1544
+
1545
+ capital_words = len(capital_words)
1546
+
1547
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
1548
+ return capital_words < self._frequency
1549
+ else:
1550
+ return capital_words >= self._frequency
1551
+
1552
+
1553
+ class QuotationChecker(Instruction):
1554
+ """Checks response is wrapped with double quotation marks."""
1555
+
1556
+ def build_description(self):
1557
+ """Build the instruction description."""
1558
+ self._description_pattern = (
1559
+ "Wrap your entire response with double quotation marks."
1560
+ )
1561
+ return self._description_pattern
1562
+
1563
+ def get_instruction_args(self):
1564
+ """Returns the keyword args of build description."""
1565
+ return None
1566
+
1567
+ def get_instruction_args_keys(self):
1568
+ """Returns the args keys of `build_description`."""
1569
+ return []
1570
+
1571
+ def check_following(self, value):
1572
+ """Checks if the response is wrapped with double quotation marks."""
1573
+ value = value.strip()
1574
+ return len(value) > 1 and value[0] == '"' and value[-1] == '"'