최근 가장 주목을 받는 언어모델은 GPT-4입니다. 그러나 API를 이용하여 Output을 얻으면 다른 결과를 얻게 되는 문제가 있습니다. 또한, ChatGPT를 이용하여 같은 질문을 하여도 GPT-4 API를 사용한 것과 다른 결과가 나오는 것을 볼 수 있습니다. 왜 이러한 문제가 발생되는지에 대해서 궁금해서 찾아보게 되었고, 찾은 내용을 공유드리고자 합니다.
GPT-4 API개요
Google Deepmind는 오래 전에 이 문제를 알고 있었을 것입니다. 올해는 LLM(Large Language Model)이 AI 분야에서 가장 큰 관심의 대상이 되었고, OpenAI의 ChatGPT와 GPT-4가 더욱 인기를 끌고 있습니다. GPT-4는 자연어 이해 및 생성, 논리적 추론, 코드 생성 등에서 놀랍습니다. 그러나 사람들은 점차 GPT-4의 생성 결과에 큰 불확실성이 있음을 발견했습니다. 사용자가 입력한 질문의 경우 GPT-4에서 제공하는 답변은 종종 무작위입니다.
우리는 생성된 결과의 다양성과 무작위성을 제어하는데 사용되는 대형 모델에 temperature 매개변수가 있다는 것을 알고 있습니다. temperature를 0으로 설정하는 것은 그리디 샘플링을 의미하며 모델의 생성된 결과는 결정적이어야 하지만 GPT-4의 생성된 결과는 temperature가 0.0인 경우에도 여전히 무작위적입니다.
Openai 커뮤니티에서 누군가가 직접 아래 질문을 했고 대답은 이랬습니다.
위 대화를 한글로 번역하면 다음과 같습니다.
내 실험들은 지금까지 파이썬과 P5.js (자바스크립트 위에 구축)를 포함하고 있으며, T=0의 동일한 프롬프트와 매개변수 설정으로 단일 응답/완성을 얻을 수 없었습니다. 예를 들어, 나는 Codex에게 “화면에 공을 튕기게 해라”라고 요청할 수 있습니다. 나는 적절한 코드를 얻기 위해 몇 번의 샷 프라이머로 사용되는 사전 설정을 만들었습니다. 생성된 코드는 매번 다릅니다. 결정론을 얻기 위한 권장 매개변수 설정 (또는 특정 프롬프트 조정)이 있나요? 나는 비슷한 질문을 봤지만, Challenge 프롬프트를 재현하는 것과 관련되어 있었습니다.
지금까지 나는 그것을 좋아한다면 P5.js 스케치를 저장했습니다. 그것은 아카이브를 제공하고 재현성을 증진시킵니다.
GPU 계산에서 부동 소수점 연산 주변에 본질적인 비결정성이 있습니다. 로그 확률의 차이는 매우 작지만, 상위 두 개의 가능성 있는 토큰 사이에 작은 차이가 있을 때, 가끔 다른 토큰이 선택될 수 있으며 이로 인해 다른 결과가 나타날 수 있습니다.
GPU 계산에서 부동 소수점 연산 주변에는 본질적인 비결정성이 있으며, 로그 확률의 차이는 매우 작습니다. 그러나 가장 가능성 있는 두 토큰 사이에 작은 차이가 있을 경우, 가끔 다른 토큰이 선택될 수 있어 결과가 다를 수 있습니다.
출처: https://community.openai.com/t/a-question-on-determinism/8185
2021년 초 일부 네티즌들이 OpenAI Codex에 대해 이 질문을 제기했다는 점은 주목할 가치가 있습니다.
이것은 이 무작위성에 대한 더 깊은 이유가 있을 수 있음을 의미합니다.
실험
Sherman Chann이라는 분이 이와 관련된 자세한 실험을 해두신 게 있어서 참고해왔습니다.
Sherman Chann의 이 블로그는 Soft MoE에 대한 Google DeepMind의 최근 논문 “From Sparse to Soft Mixtures of Experts“의 section2.2 영감을 받았다고 합니다.
Per-sequence determinism Under capacity constraints, all Sparse MoE approaches route tokens in groups of a fixed size and enforce (or encourage) balance within the group. When groups contain tokens from different sequences or inputs, these tokens often compete against each other for available spots in expert buffers. As a consequence, the model is no longer deterministic at the sequence-level, but only at the batch-level, as some input sequences may affect the final prediction for other inputs. Models using larger groups tend to provide more freedom to the routing algorithm and usually perform better, while their computational cost is also higher. On the other hand, when groups contain tokens from a single sequence, the model is forced to use
section2.2
every expert on every input sequence. This may lead to more generalist experts. Moreover, changing the group size between training and inference can be problematic due to the potential distributional shift in token-to-expert assignments. We explore these aspects in Section 3.5.
즉, Sherman Chann은 다음과 같이 가정합니다. “sparse MoE 모델의 배치 추론은 GPT-4 API에서 대부분의 불확실성의 근본 원인입니다.” 이 가설을 테스트하기 위해 Sherman Chann은 GPT-4를 사용하여 코드 스크립트를 작성했습니다.
GPT-4 API는 일괄 추론을 수행하는 백엔드와 함께 호스팅됩니다. 무작위성 중 일부는 다른 요인으로 인한 것일 수 있지만, API의 비결정성 대부분은 시퀀스별 결정성을 적용하지 못하는 드문 MoE 아키텍처 때문입니다.
import os
import json
import tqdm
import openai
from time import sleep
from pathlib import Path
chat_models = ["gpt-4", "gpt-3.5-turbo"]
message_history = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Write a unique, surprising, extremely randomized story with highly unpredictable changes of events."}
]
completion_models = ["text-davinci-003", "text-davinci-001", "davinci-instruct-beta", "davinci"]
prompt = "[System: You are a helpful assistant]\n\nUser: Write a unique, surprising, extremely randomized story with highly unpredictable changes of events.\n\nAI:"
results = []
import time
class TimeIt:
def __init__(self, name): self.name = name
def __enter__(self): self.start = time.time()
def __exit__(self, *args): print(f"{self.name} took {time.time() - self.start} seconds")
C = 30 # number of completions to make per model
N = 128 # max_tokens
# Testing chat models
for model in chat_models:
sequences = set()
errors = 0 # although I track errors, at no point were any errors ever emitted
with TimeIt(model):
for _ in range(C):
try:
completion = openai.ChatCompletion.create(
model=model,
messages=message_history,
max_tokens=N,
temperature=0,
logit_bias={"100257": -100.0}, # this doesn't really do anything, because chat models don't do <|endoftext|> much
)
sequences.add(completion.choices[0].message['content'])
sleep(1) # cheaply avoid rate limiting
except Exception as e:
print('something went wrong for', model, e)
errors += 1
print(f"\nModel {model} created {len(sequences)} ({errors=}) unique sequences:")
print(json.dumps(list(sequences)))
results.append((len(sequences), model))
# Testing completion models
for model in completion_models:
sequences = set()
errors = 0
with TimeIt(model):
for _ in range(C):
try:
completion = openai.Completion.create(
model=model,
prompt=prompt,
max_tokens=N,
temperature=0,
logit_bias = {"50256": -100.0}, # prevent EOS
)
sequences.add(completion.choices[0].text)
sleep(1)
except Exception as e:
print('something went wrong for', model, e)
errors += 1
print(f"\nModel {model} created {len(sequences)} ({errors=}) unique sequences:")
print(json.dumps(list(sequences)))
results.append((len(sequences), model))
# Printing table of results
print("\nTable of Results:")
print("Num_Sequences\tModel_Name")
for num_sequences, model_name in results:
print(f"{num_sequences}\t{model_name}")
Sherman Chann은 아래와 같이 결정을 지었습니다.
- 모든 사람들은 OpenAI의 GPT 모델이 온도가 0일 때 비결정론적임을 알고 있습니다.
- 이것은 일반적으로 비결정론적 CUDA 최적화 부동 소수점 연산의 부정확함에 기인한다고 여겨집니다. 저는 다른 가설을 제시합니다: 희소 MoE 모델에서의 일괄 추론이 GPT-4 API의 대부분의 비결정론성의 근본 원인이라고 주장합니다.
- 이것이 이전의 가설보다 더 깔끔한 가설인 이유를 설명합니다.
- 저는 경험적으로 GPT-4(및 잠재적으로 일부 3.5 모델)에 대한 API 호출이 다른 OpenAI 모델보다 훨씬 더 비결정론적임을 실증적으로 보여줍니다.
- 저는 GPT-3.5-turbo도 속도 + 비결정론성 + logprobs 제거로 인해 MoE일 수 있다고 추측합니다.
다른 개발자들은 어떻게 생각할까?
이 블로그가 게시된 후 개발자들도 GPT-4 출력의 불확실성에 대해 논의하기 시작했습니다.
어떤 사람들은 이것이 “다중 스레드 병렬 처리” 때문일 수 있다고 생각합니다.
또한 “계산이 결정적이지만 계산을 수행하는 여러 프로세서 간에 클럭 주파수 편차가 있을 수 있습니다”라고 명시되어 있습니다.
Sherman Chann의 가설을 지지한 한 개발자는 “GPT-3.5-Turbo는 GPT-4용으로 구축된 작은 테스트 모델 OpenAI일 수 있습니다.”라고 말했습니다.
또 다른 개발자는 다음과 같이 분석했습니다. “Soft MoE 논문에 따르면 sparse MoE는 불확실성을 가져올 뿐만 아니라 전문가 모듈 할당을 위해 경쟁하는 동시 요청 수에 따라 모델의 응답 품질이 달라질 수 있습니다.”