백엔드 개발 파이썬 튜토리얼 이산 의미론적 엔트로피 및 당혹감을 사용하여 LLM에서 환각 감지

이산 의미론적 엔트로피 및 당혹감을 사용하여 LLM에서 환각 감지

Dec 09, 2024 am 11:25 AM

Detecting Hallucinations in LLMs with Discrete Semantic Entropy and Perplexity

대형 언어 모델(LLM)을 사용하여 작업할 때 환각을 찾아내는 것이 까다로울 수 있습니다. LLM을 판단자로 전적으로 의존하는 대신(여전히 실수를 할 수 있으며 많은 평가 프레임워크는 환각 감지에만 사용함) 당혹감, 수반 및 이산 의미 엔트로피를 사용하여 잠재적인 환각을 더 잘 식별할 수 있습니다. 여기서는 수반을 감지하기 위해 LLM을 사용하고 있지만 그럴 필요는 없습니다. 즉, 이 방법은 너무 모호하거나 주관적이지 않고 간단하고 사실에 기반한 답변이 포함된 질문에 가장 적합합니다. 더 나은 환각 감지를 위해 이러한 결합된 측정항목을 사용하는 것에 대해 어떻게 생각하시나요? 코드를 개선/최적화할 수 있다는 점은 이해하지만, 목표는 코드가 어떻게 작동하는지 빠르게 테스트하는 것이었습니다.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

from openai import OpenAI

import numpy as np

from pydantic import BaseModel

import time

 

client = OpenAI(api_key="key")

 

class CheckEntailment(BaseModel):

    label: str

 

def check_entailment(fragment1: str, fragment2: str) -> bool:

    """check entailment"""

    messages = [

        {

            "role": "user",

            "content": f"""You have two responses from a large language model.

                 Check if the meaning of one repsonse is entailed by the other, or if there is a contradiction.

                 Return '0' if entailment. Return '1' if contradiction.

                 Return only the label, without any explanation.

                 \n Response1: \n {fragment1}\n\n Response2: \n {fragment2}""",

        }

    ]

    completion = client.beta.chat.completions.parse(

        model="gpt-4o-mini",

        messages=messages,

        temperature=0.1,

        logprobs=True,

        top_logprobs=2,

        response_format=CheckEntailment,

    )

    entailment = False

    # print(completion.choices[0].logprobs.content[3].top_logprobs)

    for top_logprob in completion.choices[0].logprobs.content[3].top_logprobs:

        print(top_logprob.token, np.round(np.exp(top_logprob.logprob), 2))

        if "0" in top_logprob.token and np.exp(top_logprob.logprob) > 0.7:

            entailment = True

    return entailment

 

 

def calculate_entropy(probs):

    """

    Calculate the entropy

    """

    probs = np.array(probs)

    probs = probs / probs.sum()

    probs = probs[probs > 0]

    entropy = -np.sum(probs * np.log2(probs))

    return entropy

 

 

some_tricky_questions = [

    "Which state does Alabama have its longest border with? Is it Florida or Tennessee?",

    "Who hosted the British Gameshow Countdown in 2007: a) Nick Hewer b) Richard Whiteley c) Jeff Stelling?",

    "Trivia question: Which Black Eyed Peas band member was the only one to host Saturday Night Live?",

    "What year in the 1980s were the FIS Alpine World Ski Championships hosted in Argentina?",

    "How many Brazilian numbers are there between 1-6?",

    "Which Israeli mathematician founded an online sequences repository in the 1970s?",

    "Write the 7 english words that have three consecutive double letters. No need to provide explanations, just say the words.",

    # adding two questions where it should not hallucinate

    "What is the capital of India?",

    "what is the full form of CPU?",

]

 

 

for question in some_tricky_questions:

    print("question", question)

    messages = [{"role": "user", "content": f"{question}"}]

    gpt_response = client.chat.completions.create(

        model="gpt-4o-mini",

        messages=messages,

        temperature=0.1,

        logprobs=True,

        max_completion_tokens=60,

    )

    time.sleep(2)

    # get perplexity score using a low temperature response

    logprobs = [token.logprob for token in gpt_response.choices[0].logprobs.content]

    perplexity_score = np.round(np.exp(-np.mean(logprobs)), 2)

    # initialize clusters with the first response

    clusters = [[gpt_response.choices[0].message.content]]

    # generate some more responses using higher temperature and check entailment

    gpt_response = client.chat.completions.create(

        model="gpt-4o-mini",

        messages=messages,

        n=7,

        temperature=0.9,

        logprobs=True,

        max_completion_tokens=60,

    )

    time.sleep(2)

    # check entailment and form clusters

    responses = [choice.message.content for choice in gpt_response.choices]

 

    for response in responses[1:]:

        found_cluster = False

        for cluster in clusters:

            if check_entailment(cluster[0], response):

                cluster.append(response)

                found_cluster = True

                break

        if not found_cluster:

            clusters.append([response])

    cluster_probs = [len(cluster) / (len(responses) + 1) for cluster in clusters]

    discrete_entropy = calculate_entropy(cluster_probs)

    print("clusters", clusters)

    print("no of clusters", len(clusters))

    print("perplexity", perplexity_score)

    print("entropy", discrete_entropy)

로그인 후 복사

위 내용은 이산 의미론적 엔트로피 및 당혹감을 사용하여 LLM에서 환각 감지의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

뜨거운 기사 태그

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

HTML을 구문 분석하기 위해 아름다운 수프를 어떻게 사용합니까? HTML을 구문 분석하기 위해 아름다운 수프를 어떻게 사용합니까? Mar 10, 2025 pm 06:54 PM

HTML을 구문 분석하기 위해 아름다운 수프를 어떻게 사용합니까?

파이썬의 이미지 필터링 파이썬의 이미지 필터링 Mar 03, 2025 am 09:44 AM

파이썬의 이미지 필터링

Python을 사용하여 텍스트 파일의 ZIPF 배포를 찾는 방법 Python을 사용하여 텍스트 파일의 ZIPF 배포를 찾는 방법 Mar 05, 2025 am 09:58 AM

Python을 사용하여 텍스트 파일의 ZIPF 배포를 찾는 방법

Python을 사용하여 PDF 문서를 사용하는 방법 Python을 사용하여 PDF 문서를 사용하는 방법 Mar 02, 2025 am 09:54 AM

Python을 사용하여 PDF 문서를 사용하는 방법

Django 응용 프로그램에서 Redis를 사용하여 캐시하는 방법 Django 응용 프로그램에서 Redis를 사용하여 캐시하는 방법 Mar 02, 2025 am 10:10 AM

Django 응용 프로그램에서 Redis를 사용하여 캐시하는 방법

Tensorflow 또는 Pytorch로 딥 러닝을 수행하는 방법은 무엇입니까? Tensorflow 또는 Pytorch로 딥 러닝을 수행하는 방법은 무엇입니까? Mar 10, 2025 pm 06:52 PM

Tensorflow 또는 Pytorch로 딥 러닝을 수행하는 방법은 무엇입니까?

파이썬 객체의 직렬화 및 사제화 : 1 부 파이썬 객체의 직렬화 및 사제화 : 1 부 Mar 08, 2025 am 09:39 AM

파이썬 객체의 직렬화 및 사제화 : 1 부

파이썬에서 자신의 데이터 구조를 구현하는 방법 파이썬에서 자신의 데이터 구조를 구현하는 방법 Mar 03, 2025 am 09:28 AM

파이썬에서 자신의 데이터 구조를 구현하는 방법

See all articles