Views
No views yet
1from typing import Dict
2
3from transformers import pipeline
4import torch
5
6
7def sample_to_str(sample: Dict[str, str]) -> str:
8 """ It converts a datapoint to an input text for an encoder-based classifier (like as RoBERTa).
9 :param sample: the datapoint
10 :return: the input text for the classifier (i.e. the LLM hallucination detector).
11 """
12 possible_tasks = {
13 'PG', # paraphrase generation
14 'MT', # machine translation
15 'DM', # definition modeling
16 }
17 checked_llm_prediction = ' '.join(sample['hyp'].strip().split())
18 llm_task = sample['task']
19 if llm_task not in possible_tasks:
20 raise ValueError(f'The task {llm_task} is not supported!')
21 if llm_task == 'PG':
22 context = ' '.join(sample['src'].strip().split())
23 united_prompt = 'The verified system\'s task is a paraphrase generation.'
24 else:
25 context = ' '.join(sample['tgt'].strip().split())
26 if llm_task== 'MT':
27 united_prompt = 'The verified system\'s task is a machine translation.'
28 else:
29 united_prompt = 'The verified system\'s task is a definition modeling.'
30 united_prompt += ' The sentence generated by the verified system: '
31 united_prompt += checked_llm_prediction
32 if united_prompt[-1].isalnum():
33 united_prompt += '.'
34 united_prompt += f' The generation context: {context}'
35 if united_prompt[-1].isalnum():
36 united_prompt += '.'
37 return united_prompt
38
39
40# The input data format is based on data for the model-agnostic track of SHROOM
41# https://helsinki-nlp.github.io/shroom
42# "src" is a verified LLM's input to start generation
43# "hyp" is an output generated by this LLM
44# "tgt" is a reference output from the point of view of human assessors
45input_data = [
46 {
47 "hyp": "Resembling or characteristic of a weasel.",
48 "ref": "tgt",
49 "src": "The writer had just entered into his eighteenth year , when he met at the table of a certain Anglo - Germanist an individual , apparently somewhat under thirty , of middle stature , a thin and <define> weaselly </define> figure , a sallow complexion , a certain obliquity of vision , and a large pair of spectacles .",
50 "tgt": "Resembling a weasel (in appearance).",
51 "model": "",
52 "task": "DM",
53 "labels": [
54 "Hallucination",
55 "Not Hallucination",
56 "Not Hallucination",
57 "Not Hallucination",
58 "Not Hallucination"
59 ],
60 "label": "Not Hallucination",
61 "p(Hallucination)": 0.2
62 },
63 {
64 "hyp": "I thought you'd be surprised at me too.",
65 "ref": "either",
66 "src": "I thought so, too.",
67 "tgt": "That was my general impression as well.",
68 "model": "",
69 "task": "PG",
70 "labels": [
71 "Hallucination",
72 "Hallucination",
73 "Hallucination",
74 "Hallucination",
75 "Hallucination"
76 ],
77 "label": "Hallucination",
78 "p(Hallucination)": 1.0
79 },
80 {
81 "hyp": "You can go with me perfectly.",
82 "ref": "either",
83 "src": "Ты вполне можешь пойти со мной.",
84 "tgt": "You may as well come with me.",
85 "model": "",
86 "task": "MT",
87 "labels": [
88 "Not Hallucination",
89 "Hallucination",
90 "Hallucination",
91 "Not Hallucination",
92 "Hallucination"
93 ],
94 "label": "Hallucination",
95 "p(Hallucination)": 0.6
96 }
97]
98
99hallucination_detector = pipeline(
100 task='text-classification',
101 model='bond005/xlm-roberta-xl-hallucination-detector',
102 framework='pt', trust_remote_code=True, device='cuda', torch_dtype=torch.float16
103)
104
105for sample in input_data:
106 input_prompt = sample_to_str(sample)
107 print('')
108 print('==========')
109 print(f' Task: {sample["task"]}')
110 print(' Question for detector:')
111 print(input_prompt)
112 print('==========')
113 print('TRUE')
114 print(f' label: {sample["label"]}')
115 print(f' p(Hallucination): {round(sample["p(Hallucination)"], 3)}')
116 prediction = hallucination_detector(input_prompt)[0]
117 predicted_label = prediction['label']
118 if predicted_label == 'Hallucination':
119 hallucination_probability = prediction['score']
120 else:
121 hallucination_probability = 1.0 - prediction['score']
122 print('PREDICTED')
123 print(f' label: {predicted_label}')
124 print(f' p(Hallucination): {round(hallucination_probability, 3)}')1
2==========
3 Task: DM
4 Question for detector:
5The verified system's task is a definition modeling. The sentence generated by the verified system: Resembling or characteristic of a weasel. The generation context: Resembling a weasel (in appearance).
6==========
7TRUE
8 label: Not Hallucination
9 p(Hallucination): 0.2
10PREDICTED
11 label: Not Hallucination
12 p(Hallucination): 0.297
13
14==========
15 Task: PG
16 Question for detector:
17The verified system's task is a paraphrase generation. The sentence generated by the verified system: I thought you'd be surprised at me too. The generation context: I thought so, too.
18==========
19TRUE
20 label: Hallucination
21 p(Hallucination): 1.0
22PREDICTED
23 label: Hallucination
24 p(Hallucination): 0.563
25
26==========
27 Task: MT
28 Question for detector:
29The verified system's task is a machine translation. The sentence generated by the verified system: You can go with me perfectly. The generation context: You may as well come with me.
30==========
31TRUE
32 label: Hallucination
33 p(Hallucination): 0.6
34PREDICTED
35 label: Not Hallucination
36 p(Hallucination): 0.4871@misc{bondarenko2024hallucination,
2 title={The reference-based detector of LLM hallucinations by Ivan Bondarenko},
3 author={Bondarenko, Ivan},
4 publisher={Hugging Face},
5 journal={Hugging Face Hub},
6 howpublished={\url{https://huggingface.co/bond005/xlm-roberta-xl-hallucination-detector}},
7 year={2024}
8}