20 May 2023
#nlp
Recurrent neural network (RNN)의 Long-term dependency 문제를 해결하고자 만들어진 프레임워크이다.
핵심적인 아이디어는 이전 시점의 state 정보를 이후 state에 얼마나 반영할지를 결정하는 계산을 추가해주는 것이다. 이것을 위해 forget gate, input gate, output gate의 3가지 Gate와 memory cell이 추가 되었다.
LSTM의 계산 방식과 비교하기 위해 RNN의 계산식을 되짚어보면 다음과 같다.
\[\begin{align*}
h_t&=\tau(Wh^{t-1}+Ux^t) \\
\hat{y}_t&=softmax(Vh^t) \\
\end{align*}\]
이전 시점($t-1$)의 hidden state와 현재 시점($t$)의 input(둘 다 weighted)을 더하여 tanh를 통과시키면 현재 시점의 hidden state가 된다. 이것에 softmax를 취하면 output이 된다.
LSTM 계산식
LSTM은 RNN의 방식에 residual connection 구조에서 착안한 memory 기능을 더하여 long-term dependency 문제를 해결하고자 했다. Memory 기능을 위해 추가된 계산들은 다음과 같다.
Forget gate
Forget gate $f$는 이전 시점의 정보를 얼마나 잊을지 결정하는 gate이다.
\[f_t=\sigma(W_fh_{t-1}+U_fx_t)\]
이전 시점의 hidden state와 현재 시점의 input을 더한 뒤 sigmoid를 취한다. 이것이 이전 시점의 memory cell state에 곱해진다. sigmoid의 특성에 의해 1에 가까울수록 이전 정보가 이후 많이 반영된다.
Input gate $i$는 현재 시점의 input을 다음 시점에 얼마나 반영할지 결정하는 gate이다. 여기서 candidate $\hat(c)$라는 개념이 등장하는데, candidate는 이전 시점의 hidden state와 현재 시점의 input을 고려했을 때 현재의 정보가 어떠한지를 나타내는 cell state의 후보 격인 값이다. 계산 방식이 RNN의 hidden state와 동일하다. input gate 값과 candidate를 곱해 현재의 정보 상 input이 얼마나 반영되면 좋은지를 구하고, 이것을 최종적으로 cell state에 더한다.
\[\begin{align}
i_t&=\sigma(W_{in}h_{_t-1}+U_{in}x_{t})\\
\hat{C}_t&=\tau(W_{c}h_{t-1}+U_{c}x_t)
\end{align}\]
Memory cell
Memory cell (cell state)은 세 가지 gate와 함께 LSTM의 구현 목적을 위해 추가된 개념이다. 현재 시점의 cell state는 이전 시점의 cell state 및 현재 시점의 forget gate와 현재 시점의 input gate 및 candidate로 계산한다.
\[C_t=f_t*C_{t-1}+i_t*\hat{C}_t\]
$*$는 pointwise operation
이전 정보인 cell state와 현재 input을 얼마나 반영할지가 합해져 현재 시점의 cell state가 구해진다.
Output gate
Output gate는 memory cell을 현재 시점의 hidden state에 얼마나 반영할지 결정한다.
\[\begin{align}
o_t&=\sigma(W_oh_{t-1}+U_ox_t) \\
h_t&=o_t\tau(C_t) \\
&=o_t\tau(f_t*C_{t-1}+i_t*\hat{C}_t) \\
\end{align}\]
현재 시점의 hidden state는 이전 시점의 정보와 현재 시점의 input이 반영된 현재 시점의 cell state와 output gate의 결과값과 곱해져 최종 결정된다.
Output
최종 출력 $\hat{y}_t$은 RNN과 같이 계산된다.
\[\hat{y}_t=softmax(Vh_t)\]
LSTM의 한계
LSTM은 cell state 도입을 통해 gradient vanishing 문제를 해결하고자 하였다. 하지만 RNN 구조를 기반으로 하고 있는 한 이 문제를 완벽하게 해결하기에 한계가 있다. 오히려 gate를 여러 개 사용하여 계산량이 증가하는 문제가 있다.
15 May 2023
#nlp
#llm
Paper Link
Points
- Alpaca aims to support academic research on instruction-following large language models (LLMs), addressing deficiencies like hallucinations, toxicity, and biases.
- Uses the self-instruct approach to create an instruction-following dataset with text-davinci-003, costing under $500.
- The LLaMA 7B model is fine-tuned using efficient techniques.
Background
LLMs trained through instruction-following, such as ChatGPT, have significantly impacted daily life. However, these models still face issues like generating misinformation, toxic content, and exhibiting social biases. To address these problems, academic research is essential. Closed-source models hinder this research, making it difficult to study instruction-following models.
Alpaca is a model designed for academic research, fine-tuned from the LLaMA 7B model using 52k instruction-following data generated from OpenAI’s text-davinci-003. Commercial use of Alpaca is prohibitied by following reasons:
- Non-commercial license: LLaMA
- Data restrictions: Based on text-davinci-003 prohibiting competition with OpenAI
- Deployment caution: Not designed with adequate safety mesuares for general use.
Training Recipe
To train a high-quality instruction-following model under an academic budget, two key challenges are addressed:
- Strong pre-trained language model: LLaMA models
- High-quality instruction-following data: Self-instruct method
Self-instruct method
- Seed set: 175 human-written instruction-following output pairs from self-instruct seed set.
- Data generation: Prompting text-davinci-003 to generate more instructions using the seed set as examples.
- Efficiency: Improved the self-instruct method, generating 52k unique instructions and outputs for less than $500 using the OpenAI API.
Fine-tuning the model
- Process: LLaMA models are fine-tuned with the generated instruction-following dataset using fully shared data parallel (FSDP) and mixed precision trianing.
- Cost and time: Fine-tuning a 7B LLaMA model took 3 hours on eight 80GB A100s, costing less than $100 on most cloud compute providers.
Preliminary Evaluation
Human evaluation was conducted on inputs from the self-instruct evaluation set. Key findings include:
- Comparison: Alpaca 7B vs. text-davinci-003
- Performance: Alpaca wins 90 to 89 comparisons.
- Given Alpaca’s smaller size and limited data, it performed similarly to text-davinci-003.
- Generation style: Alpaca’s outputs tend to be similar with text-davinci-003, and reflect the general style of the training dataset.
- Evaluation limitation: The evaluation data’s limitations should be noted.
- An interactive demo was released to gather further feedback.
Known Limitiations
Alpaca shares common deficiencies with LLMs, such as hallucinations, toxicity, and stereotypes. It struggles particularly with hallucination, sometimes producing well-written misinformation. Despite these issues, Alpaca provides a lightweight model for studying these deficiencies, aiding academic research.
Release
Released assets:
- Demo: Interactive demo for evaluation
- Data: 52k demonstrations used to fine-tune Alpaca
- Data generation process: Code for generating the data
- Training code: Fine-tuning code using Hugging Face API
Future release:
- Model weights: Pending guidance from Meta
The release aims to support academic studies on instruction-following LMs and developing new technique to address the existing deficiencies.
10 May 2023
#nlp
#llm
Touvron, Hugo, et al. “Llama: Open and efficient foundation language models.” arXiv preprint arXiv:2302.13971 (2023).
Paper Link
Points
- 효율적 inference를 위한 smaller model: LLaMA 모델은 효율성을 위해 대규모 데이터셋으로 학습된 작은 사이즈의 모델을 사용한다. 특히 inference 시 비용 면에서 효율적일 뿐 아니라 state-of-the-art (SOTA)의 성능을 달성했다.
- Publicly available data: 기존의 많은 모델은 공개되지 않는 독점 데이터를 사용해 학습되었다. 이와 달리 LLaMA는 공개된 데이터만으로 학습되어 투명성 및 호환성, 오픈 소스 원칙을 보장한다.
- 다양한 Benchmark Performance: LLaMA 모델은 common sense reasoning, question answering, reading comprehension 등 다양한 task에서 경쟁력 있는 성능을 보여주었고, 더 큰 사이즈의 모델을 능가하기도 한다.
Background
Large language model (LLM)은 최소한의 지시(instruction)나 예제로도 새로운 task를 수행할 수 있는 능력을 보여주었다. 그러나 최근 연구에 따르면 작은 모델을 큰 데이터셋으로 학습하면, 큰 사이즈 모델 이상의 성능을 달성할 수 있다는 것이 보고되었다. 한편 모델을 실시간으로 서빙해야 하는 관점에서 보면 학습 도중의 효율성보다는 inference 시 비용 절감과 효율성 확대가 더 중요하다.
Approach
LLaMA는 다양한 inference 비용에 맞춰 최적화된 성능을 내도록 설계된 언어 모델 (LM) 시리즈로, 7B부터 65B 파라미터를 갖는다. 모든 모델은 공개된 데이터만을 사용하여 학습되었다.
Pre-training data
오픈 소스 원칙을 보장하는, 다양한 도메인의 공개 데이터셋을 사용했다:
- English CommonCrawl [67%]: 2017-2020년의 다섯 개 CommonCrawl dump에서 전처리한 데이터를 사용했고, 영어가 아니거나 품질이 낮은 콘텐츠는 필터링했다.
- C4 [15%]: CommonCrawl과 유사하게 전처리되었다. 이 전처리 방식이 성능 향상에 도움이 되는 것으로 보인다.
- Github [4.5%]: Google BigQuery에서 line 수와 알파벳 문자 비율을 기준으로 필터링하여 구성하였다.
- Wikipedia [4.5%]: 2022년 중반의 덤프 데이터로 여러 언어를 포함한다.
- Gutenberg and Books3 [4.5%]: 공개적으로 사용 가능한 서적 데이터로, 중복 콘텐츠를 제거했다.
- ArXiv [2.5%]: 과학 관련 내용을 포함하는 데이터로, 필수적이지 않은 내용은 제거했다.
- Stack Exchange [2%]: 점수에 따라 정렬하여 퀄리티가 좋은 것을 골라낸 Q&A 콘텐츠 데이터이다.
Tokenization
Architecture
LLaMA 모델은 Transformer 구조를 기반으로 하는데, 몇 가지 수정된 사항이 있다:
- Pre-normalization [GPT3]: 각 Transformer 하위 레이어의 입력을 RMSNorm을 사용해 정규화하여 학습 안정성을 강화했다.
- SwiGLU activation function [PaLM]: ReLU 대신 SwiGLU를 사용해 성능을 향상시켰다. PaLM에서 사용된 $4d$ 대신 $2\over3 4d$ 차원을 사용한다.
- Rotary Embeddings [GPTNeo]: 각 레이어에서 absolute positional embedding 대신 Rotary embedding (RoPE)을 사용했다.
Optimizer
AdamW optimizer를 사용해 학습한다. 최적화 옵션은 다음과 같다:
Efficient implementation
- Causal multi-head attention: xformer library를 사용해 메모리와 실행 시간을 효율적으로 줄이고자 하였다.
- Activation reductions: 체크포인팅을 사용해 backward pass 동안, 특히 계산 비용이 많이 드는 레이어에 대해 activation을 다시 계산한다.
Main Results
20개의 벤치마크에서 zero-shot 및 few-shot task로 평가했고, GPT-3, Gopher, Chinchilla, PaLM 등 비공개 모델 및 OPT, GPT-J, GPT-Neo 등의 오픈 소스 모델과 결과를 비교했다.
Common sense reasonging
- Benchmarks: BoolQ, PIQA, SIQA, HellaSwag, WinoGrande, ARC easy and challenge, OpenBookQA의 8개 표준 벤치마크에 대해 평가했다. 이 데이터셋들에는 Cloze 및 Winograd style task와 multiple choice question answering (QA)이 포함된다.
- Results
- LLaMA-65B는 대부분의 벤치마크에서 Chinchilla 70B와 PaLM-540B를 능가했다.
- LLaMA-13B는 훨씬 작은 사이즈의 모델임에도 대부분의 벤치마크에서 GPT-3보다 좋은 성능을 보였다.
Close-book question answering
- Benchmarks: Natural Questions과 TriviaQA. 모델은 질문에 대한 답에 관련된 단서를 참조하지 않고도 답을 얼마나 잘 맞추는지를 평가 받는다.
- Results:
- LLaMA-65B zero-shot과 few-shot 세팅 모두에서 state-of-the-art (SOTA) 성능을 달성했다.
- LLaMA-13B은 더 큰 모델인 GPT-3와 Chinchilla에 뒤쳐지지 않는 성능을 보였다.
Reading comprehension
- Benchmark: RACE reading comprehension 벤치마크를 사용했다. 중국 중고등학교 영어 독해 시험에서 수집되었다.
- Results: LLaMA-65B는 PaLM-540B와 유사한 성능을 보였고, LLaMA-13B는 GPT-3을 능가했다.
Mathematical reasoning
- Benchmarks: MATH와 GSM8k 벤치마크를 사용했다. MATH는 12,000개 중고등학교 수학문제, GSM8k는 중학교 수준 수학 문제로 구성된다.
- Results: LLaMA-65B는 GSM8k에서 Minerva-62B를 뛰어 넘은 성능을 보였다.
- Minerva는 ArXiv와 Math Web Pages에서 추출한 38.5B개 토큰으로 fine-tune된 PaLM model 시리즈이다. 한편 PaLM과 LLaMA는 수학 문제 데이터에 finetune 되지 않았다.
Code generation
- Benchmarks: HumanEval과 MBPP 벤치마크를 사용했다. 모델은 자연어로 묘사한 내용을 보고 코드를 작성하는 능력에 대해 평가된다.
- Results:
- LLaMA 모델은 LaMDA와 PaLM을 포함한 다른 모델을 능가한다. LLaMA-13B는 LaMDA-137B를, LLaMA 65B는 PaLM-62B보다 좋은 성능을 보였다.
- 코드에 특화된 데이터로 fine-tune하면 성능이 더욱 향상되는 것을 볼 수 있었다.
Massive multitask language understanding
- Massive multitask language understanding (MMLU): MMLU는 인문학, STEM, 사회과학 등 다양한 영역의 지식을 포괄하는 다중 선택 질문으로 구성된다.
- Results: LLaMA-65B는 Chinchilla-70B와 PaLM-540B에 비해 낮은 성능을 보였는데, 이것은 학술적인 데이터를 다른 모델 만큼 충분히 학습하지 않았기 때문인 것으로 추측된다.
- Result: 성능은 학습 중 지속적으로 향상된다. 또한 성능과 모델의 복잡성 간 상관관계가 나타났다.
- SIQA와 WinoGrande에 대해서는 예외적인 결과를 보였다: SIQA의 경우 성능의 변동이 나타나는 것으로 보아 신뢰하기 어려운 벤치마크일 가능성이 있다. WinoGrande에서는 모델 복잡성과 성능 간 관계성이 나타나지 않았다.
Instruction Fine-tuning
Fine-tuning은 성능을 향상시키고 instruction을 따르는 능력을 개선한다. LLaMA-I는 MMLU에 대해 instruction과 함께 fine-tune한 모델이다. 이를 비슷한 사이즈를 가지는 finetuned 모델인 OPT-IML 및 Flan-PaLM 시리즈와 비교했다.
- 65B 파라미터의 LLaMA-I는 기존 instruction fine-tuned 모델보다 좋은 성능을 보였다. 그러나 GPT ‘code-davinci-002’에는 미치지 못했다.
LLM은 학습 데이터의 내용에 따라 편향을 가질 수 있으며, 공격적인(toxic/offensive) 콘텐츠를 생성할 수 있다. LLaMA 모델은 웹에서 수집한 데이터를 많이 학습했기 때문에 이러한 콘텐츠 생성의 가능성을 확인할 필요가 있다. toxic content generation 및 stereotypes detection을 평가하기 위해 다양한 벤치마크를 사용했다.
RealToxicityPrompts
모델이 toxic 콘텐츠를 얼마나 생성하는지를 평가하는 벤치마크이다. 모델은 약 10만개의 프롬프트를 완성하고, 점수는 PerspectiveAPI에 의해 0(non-toxic)부터 1(toxic)로 자동 평가된다.
- LLaMA는 다른 모델과 비슷한 toxic score를 얻었다. 예를 들어 Chinchilla의 경우 0.087의 toxicity score를 보였다.
- 모델이 클수록 toxicity가 강하게 나타났다. 이전 연구에서도 유사한 결과가 있었다. 한편 Gopher와 Chinchilla의 경우 Gopher가 사이즈가 더 작음에도 Chinchilla보다 더 toxic하다고 평가된 바가 있어 예외적이었다. 이를 고려할 때 toxicity와 모델 크기 간 관계가 같은 모델 시리즈 내에서만 적용된다고 짐작할 수 있다.
CrowS-Pairs
모델의 bias를 9개 카테고리에 따라 평가한다: gender, religion, race, sexual orientation, age, nationality, disability, physical appearance 및 socioenconomic status.
- LLaMA는 특히 religion, age 및 gender 카테고리에서 약간의 bias를 보였다. 모델이 학습한CommonCrawl 데이터에서 비롯된 것일 수 있다.
WinoGender
모델의 gender 카테고리에 대한 bias를 체크하기 위한 벤치마크이다. 모델의 co-reference resolution 성능이 성별 관련 대명사에 영향을 받는지를 평가한다. 특히 직업과 관련된 사회적 편견을 모델이 학습했는지를 볼 수 있다.
- 성능은 성별 대명사의 종류에 따라 다양하게 나타났다: “her/her/she”와 “his/him/he” 대명사에 관한 성능보다 “their/them/someone” 대명사에서 관한 성능이 더 좋다.
- 큰 모델이 더 큰 gender bias를 가졌다: “gotcha” 사례의 경우, LLaMA-65B가 더 큰 에러를 보이며 gender에 대해 더 편향되어 있음을 보였다.
- “gotcha”는 해당 사례 내 대명사가 보편적이라고 인식되는 직업의 대명사와 일치하지 않는데, 그것이 옳은 답변인 경우를 말한다.
TruthfulQA
모델이 내용의 진위 여부를 판단할 수 있는지를 평가하고, 잘못된 정보를 생성할 위험을 얼마나 갖는지 측정한다. 모델 답변의 truthfulness를 평가한다.
- LLaMA 모델은 GPT-3보다 나은 결과를 보였다. 하지만 여전히 정답률이 낮기 때문에 잘못된 정보를 생성할 가능성이 있다.
모델 훈련과 배포에 있어 환경에 미치는 영향을 설명한다.
30 Apr 2023
#nlp
#llm
Ouyang, Long, et al. “Training language models to follow instructions with human feedback.” Advances in neural information processing systems 35 (2022): 27730-27744.
Paper Link
Point
- Employs Reinforcement Learning from Human Feedback (RLHF) to fine-tune GPT-3 models, aligning them with human intentions while reducing unintended behaviors like hallucinations and toxicity.
- InstructGPT models outperforms GPT-3 in truthfulness and reliability, generalizing well to new tasks like non-English and coding instructions.
- Highlights the need for diverse stakeholder input and suggest combining RLHF with other methods to improve model alignment and safety.
Background
Language models (LMs) often generate misinsformation, toxic or biased content and this issue cannot be resolved simply by increasing the model size. Understanding user intent is crucial for these models. Fine-tuning with human feedback can align the models with user intentions across various tasks.
Large language models (LLMs) frequently exhibit uninteded behaviors, such as hallucinations, toxic text generation, failing to follow user instructions. These are influenced by the model’s objective, which typically involves predicting the next token based on web data, differing from the goal of “following the user instructions helpfully and safely”.
To align LMs, this paper employs Reinforcement Learning from Human Feedbak (RLHF) to fine-tune GPT-3 to follow instructions. Human preferences serve as a reward signal for this fine-tuning process.
Methods and experimental details
High-level methology
- Preparation: Utilize pre-trained language models (GPT-3), prepare a distribution of prompts for alignment, and train human labelers.
- Collect demonstration data and train a supervised policy: Labelers provide input prompts as desired behavior responses. The model is fine-tuned on this data using supervised learning.
- Collect comparison data and train a reward model: Labelers compare model outputs and indicate their preferences. A reward model (RM) is trained using these comparisons to predict human-preferred outputs.
- Optimize a policy aganst the RM using PPO: The RM’s output serves as a scalar reward. The supervised policy (trained GPT-3) is fine-tuned using the PPO algorithm to optimize this reward.
Step 2 and 3 can be iterative: More comparison data is collected on the current best policy, used to train a new RM and subsequently a new policy.
Dataset
Source of prompts:
- Consists of text prompts submitted to the OpenAI API, specifically those using an earlier version of InstructGPT models on the Playground interface.
- The paper does not include data from customers using the API in production.
Deduplication and filtering:
- Heuristically deduplicated by checking for prompts that share a long common prefix.
- The number of prompts is limited to 200 per user ID.
- Validation and test sets contain no data from users whose data is in the training set.
- All prompts in the training split were filtered for personally indentifiable information (PII).
Initial source of prompts: Human-written prompts were used as an initial source of instruction to bootstrap the process.
Datasets for fine-tuning:
- SFT dataset: Labelers’ demonstrations (13k prompts, from the API and labeler-written examples).
- RM dataset: Labeler rankings of model outputs (33k, from the API and labeler-written examples).
- PPO dataset: Inputs for RLHF fine-tuning. Human labels were not used (31k, only from the API).
Use cases: Most of the use-cases have are generative, rather than classification of prompts submitted to InstructGPT models
Tasks
Datasets for training tasks
- Sources: The datasets are sourced from prompts written by labelers and those submitted to early versions of InstructGPT models via API.
- Labeler Instructions: Labelers are trained and instructed to write prompts with specific intents or implicit goals in mind to ensure the model aligns with desired behaviors.
- Language: The datasets are predominately in English (95%). However, the paper also reports the models’ performance in other languages.
Human data collection
Selection of Labelers: A diverse group of labelers was selected to ensure a broad demographic representation. It aims to generate inputs with a wide range of perspectives and to identify potentially harmful outputs.
Training and Evaluation: Labelers underwent tests designed to measure their performance in labeling according to the set standards. This included their ability to generate diverse prompts and accurately identify harmful content.
Models
Pre-trained GPT models are utilized as basis. These models are trianed on a broad distribution of Internet data and can be used for various tasks but initially exhibit poorly characterized behavior. The GPT-3 models are then further trained using three different techniques:
Supervised fine-tuning (SFT)
This method fine-tunes GPT-3 on labeler demonstrations using supervised learning.
- Training details: 16 epochs using a cosine learing rate decay and a residual dropout of 0.2.
- Model selection: Based on the model’s RM score on the validation set.
- Finding: Training for more epochs improves both the RM score and human preference ratings, depite some overfitting.
Reward modeling (RM)
- Base model: Starts with a pre-trained SFT model but the final unembedding layer is removed. This layer maps the model’s representations to the vocabulary space for generating output tokens.
- Input and output: The model takes a prompt and a response are as input and outputs a scalr reward, representing theh quality of the response for the given prompt.
- Model size: Utilizes 6B reward model (RM) for efficiency. A larger 175B RM was found to be unstable and unsuitable for use as the value function in RL.
- Data: Uses comparisons between two model outputs for the same input to determine which output is preferred by human labelers.
- Loss: Trained with cross-entropy loss, using the comparisons as labels. The reward difference reflect the log odds of one response being preferred over the other by a labeler.
- Speed-up comparison collection: Labelers are presented with $K$ responses to rank for each prompt, where $K$ ranges from 4 to 9. This results in $K(K-1) \over 2$ comparisons for each prompt.
- Training efficiency and overfitting:
- Comparisons within each labeling task are very correlated. If all comparisons are shuffled into one dataset and processed in a single pass, the model tends to overfit.
- To address this, the training treats all $K(K-1) \over 2$ comparisons from each prompt as a single batch element, offering several benefits:
- Requires only one forward pass for each set of $K$ responses, instead of $K(K-1) \over 2$ forward passes.
- Prevents overfitting by avoiding isolated highly correlated comparisons.
- Improves computational efficiency, and achieves better validation accuracy and log loss.
-
Loss function:
\[loss(\theta)=-{1\over \binom{K}{2}} E_{(x,y_w,y_l)~D}[\log(\sigma(r_\theta(x,y_w)-r_\theta(x,y_l)))]\]
- $r_\theta(x,y)$ is the scalar output of the RM for promt $x$ and completion $y$ with parameters $\theta$.
- $y_w$ is preferred completion out of the pair of $y_w$ and $y_l$.
- $D$ is the dataset of human comparisons.
Reinforcement learning (RL)
- Base model: The SFT model is fine-tuned using Proximal Policy Optimization (PPO) in an environment.
- Training environment: A bandit environment. It this context, a bandit environment presents a random customer prompt, expects a response, produces a reward determined by the RM, and ends the episode.
- Input and output: The model takes the prompt and response as input and outputs a reward determined by the RM.
- KL penalty: A per-token Kullback-Leibler (KL) penalty is added from the SFT model at each token.
- This penalty mitigates over-optimization of the RM and prevents the model from deviating too far from the behavior learned during supervised fine-tuning.
- The value funciton used in PPO is initialized from the RM.
- PPO and PPO-ptx models:
- In this paper, InstructGPT refers to the PPO-ptx models.
Baselines
The performance of PPO models is compared against several baselines:
- SFT models: Fine-tuned using supervised learing.
- GPT-3: The standard GPT-3 model without additional fine-tuning.
- GPT-3 Prompted: Provided with a few-shot previx to prompt it into an instruction-following mode, where the prefix is prepended to the user-specified instruction.
- InstructGPT is compared to 175B GPT-3 models fine-tuned on FLAN and T0 datasets. These datasets include various NLP tasks combined with natural language instructions.
Evaluation
The definition of “alignment” to evaluate models is based on their ability to act in accordance with user intentions. The practical evaluation framework checks if the model is helpful, honest and harmless.
- Helpfulness: The model should follow instructions and infer intentions from prompts or a patterns.
- Since the intention could be unclear, labeler preference ratings are considered mainly for evaluation.
- There may be divergence between actual user intentions and labeler interpretations.
- Honesty: Truthfulness is measured instead of comparing the model’s output to its actual belief.
- Two metrics are used:
- The model’s tendency to fabricate information on closed domain tasks
- Performance on the TruthfulQA dataset.
- Harm: Harmfulness depends on the context in which the model is used, and assessing potential harm requires significatn speculation.
- More specific proxy criteria are used:
- Whether a deployed model could be harmful.
- Labelers evaluate if an output is inappropriate in the context of a customer assistant, denigrates a protected class, or contains sexual or violent content.
- Benchmarks like RealToxicityPrompts and CrowS-pairs are used to measure bias and toxicity.
Evaluation on API distiribution
When using prompts from the API for evaluting human preference ratings, only prompts not included in training are selected.
Since prompts for InsturctGPT models are not suitable for the GPT-3 baselines, prompts submitted to the GPT-3 API are also used for evaluation.
- The GPT-3 prompts are not in an instruction-following style.
- The 175B SFT model is chosen as the baseline due to its average performance.
Each model is evaluated based on how often its outputs are preferred, and labelers judge the overall quality of each response on a 1-7 Likert scale.
Evaluation on public NLP datasets
Two types of public datasets are used:
- Safety evaluation: Focuses on truthfulness, toxicity, and bias. Includes evaluations of toxicity using the RealToxicityPrompts dataset.
- Zero-shot performance: Assesses performance on traditional NLP tasks such as question anwering (QA), reading comprehension, and summarization.
Results
The experimental results are organized into three parts: results on the API prompt distribution, results on public NLP datasets, and qualitative results.
Results on the API distribution
1. Labelers significantly prefer InstructGPT outputs over outputs from GPT-3.
- 175B InstructGPT outputs are preferred to GPT-3 outputs around 85% of the time and around 71% compared to few-shot GPT-3.
- The preference order is GPT-3 < GPT-3 Prompted < SFT < PPO.
- Adding updates on the pre-training mix during PPO does not lead to significant changes in labeler preference.
- This preference trend remains consistent when evaluating models on prompts submitted to GPT-3 models on the API, though PPO-ptx models perform slightly worse at larger sizes.
- InstructGPT outputs are rated favorably on more concrete axes: They follow constraints and instruction better and hallucinate less.
- This suggests that InstructGPT models are more reliable and easier to control than GPT-3.
2. InstructGPT models generalize to the preferences of “held-out” labelers that did not produce any training data.
- InstructGPT models’ outputs are rated better than GPT-3 baselines by held-out labelers, indicating InstructGPT models are not simiply overfitting to the preferences of training labelers.
- RMs also demonstrate generlization capabilties with cross-validation results: 69.6% accuracy in predicting the preferences of held-out labelers, which is slightly lower than 72.4% accuracy in the predicting preferences within the training set.
3. Public NLP datasets are not reflective of how the LMs are used.
- When comparing InstructGPT to 175B GPT-3 baseline fine-tuned on FLAN and T0, these models perform better than GPT-3 with a good prompt but worse than the SFT baseline. This suggests the datasets are not sufficiently diverse to improve API prompt distribution.
- InstructGPT may outperform FLAN and T0 because:
- Public NLP datasets are desinged to capture typical tasks that are easy to evaluate (e.g., classification, QA). However, open-ended generation and brainstorming constitute most (57%) of tasks the API users want.
- Public NLP datasets may lack the high diversity of inputs that real-world users are interested in.
Results on public NLP datasets
1. InstructGPT models show improvements in truthfulness over GPT-3.
- PPO models demonstrate significant improvements on the TruthfulQA dataset.
- The 1.3B PPO-ptx model performs slightly worse than GPT-3 of the same size.
- Training with an “Instruction+QA” prompt helps the model avoid generating false information.
- Instruction+QA: Instructs the model to respond with “I have no comment” when it’s uncertain of the correct answer.
2. InstructGPT shows small improvements in toxicity over GPT-3, but not bias.
- Toxicity: Evaluated using the RealToxicityPrompts benchmark.
- Evaluation method: Toxicity scores are obtained through the Perspective API with model samples and labelers rate the samples.
- InstructGPT outputs are less toxic than those of GPT-3 when instructed to generate respectful outputs. Without any prompt, the models are similar, and InstructGPT can be more toxic when prompted to produce toxic content.
- Bias: Evaluated using the Winogender and CrowS-Pairs benchmarks.
- Evaluation method: Calculates the relative probabilities of producing sentences in each pair and the entropy of the associated binary probability distributions.
- Unbiased models will show no preference, thus having maximum entropy.
- InstructGPT and GPT-3 show similar levels of bias. The PPO-ptx model shows higher bias when instructed to act respectfully, with unclear patterns.
- Instructed models tend to be more certain of their outputs, regardlessly with stereotypes.
- Alignment tax: PPO model experience a decrease in performance on public NLP datasets, referred to as “alignment tax”.
- Mitigation strategies: Mixing pre-training updates to the PPO fine-tuning (PPO-ptx) reduces performance regressions across all datasets.
- PPO-ptx performs better than merely increasing the KL coefficient. Changing the KL model from the PPO initialization to GPT-3 yields similar improvements.
Qualitative results
1. InstructGPT models show promising generlization to instructions outside of the RLHF fine-tuning distribution.
- InstructGPT models can follow non-English instructions, and perform coding tasks, despite limited training data in these formats.
- Alignment methods can generalize to produce desired behaviors on inputs not directly supervised.
- 175B PPO-ptx model can answer questions about code and non-English instructions, but often responds in English to questions in other languages.
2. InstructGPT still makes simple mistakes.
- The model sometimes incorrectly assumes a false premise in an instruction is true.
- It can overly hedge even when the answer is clear.
- It struggles with generating responses when there’re multiple or challenging constraints in an instruction.
Discussion
Implications for alignment research
Improving the alignment of current AI systems provides a clear empirical feedback loop, esssential for refining alignment techniques.
Moreover, RLHF is an important building block for aligning superhuman systems, especially for tasks difficult to evaluate.
General lessons for alignment research:
- The cost of increasing model alignment is modest relative to pre-training: The significant costs lie in data collection and computation. With RLHF, larger LMs become more helpful, suggesting investing in aligning existing LMs is more efficient than training new, larger models.
- There is evidence that InstructGPT generalizes ‘following instructions’ to settings that we don’t supervise it in: E.g., non-English and code tasks. This is important as creating supervised models for each task is expensive.
- The proposed fine-tuning can mitigate most of the performance degradations: Low alignment tax techniques are needed for future AI systems capable of understanding human intents, and RLHF is effective in this regard.
- Alignment techniques are validated in the real world: This work grounds alignment research in real-world applications, providing valuable insights for AI systems used by actual users.
Who are we aligning to?
Factors influencing the fine-tuning data and key sources of alignment preferences:
- Labelers’ preferences: The models are aligned to the preferences of hired labelers who generate the training data. They are mostly English speakers, with around 73% agreement among them.
- Researchers’ preferences: Researchers design the study, write instructions, and guide labelers on edge cases, thereby influencing the alignment. More research is needed to understand the impact of different instructions and interfaces on the collected data and model behavior.
- Customer prompts: Training data includes prompts from OpenAI customers using the API. There is potential misalignment between customer goals and end-user well-being.
- Customer representation: The customers are not representative of all potential or current LM users. The initial user base was biased towards OpenAI’s networks.
Challenges and future directions:
- Designing a fair and transparent alignment process is complex.
- This paper demonstrates that the alignment method can work for a specific human reference group but doesn’t claim these group preferences are ideal.
- Multiple stakeholders need consideration, including model trainers, developers, end-users, and the broader impacted population.
- Aligning a system to everyone’s preferences simultaneously is impossible, and not all trade-offs will be universally endorsed.
- One potential approach is to train models for different group preferences so that it can reflect diverse values. However, this may still impact broader society, raising decisions about prioritizing preferences.
Limitations
Methodology:
- Contractor influence: InstructGPT is influenced by the human feedback from about 40 contractors.
- Contractors’ identity, beliefs, cultural backgrounds, and personal history may affect their judgments.
- They were selected based on their performance with sensitive prompts and labeling tasks.
- The small team size allowed for better communication but is not representative of the broader population will use the models.
- They are mostly English-speaking, and the data is almost entirely in English.
- Data collection improvements: Most comparisons are labeled by only one contractor to reduce costs.
- Multiple labelings could help identify disagreement areas, indicating where a single model may not align with all labelers.
- Averaging labeler preferences for disagreements might not be ideal, especially for minority groups, whose preferences should be weighted more heavily.
Models:
- Imcomplete alignment and safety: InstructGPT is not fully aligned or safe.
- It still generates toxic or biased outputs, misinformations, and sexual or violent content.
- It sometimes fails to generate reasonable outputs for certain inputs.
- Following potentially harmful instructions: InstructGPT often follows instructions even if it could lead to real-world harm.
- It produces more toxic outputs than GPT-3 when instructed to be maximally biased.
22 Dec 2020
#cv
Wang, Zhihao, Jian Chen, and Steven CH Hoi. “Deep learning for image super-resolution: A survey.” IEEE transactions on pattern analysis and machine intelligence 43.10 (2020): 3365-3387.
Paper Link
Introduction
- Super-resolution (SR)은 저화질(low-resolution; LR) 이미지를 고해상도(high-resolution; HR) 이미지로 변환하는 과정이다.
- LR 이미지에는 여러 HR 이미지가 있을 수 있다는 점에서 SR은 불완전한 문제이다.
- Deep learning (DL)은 SR의 발전에 크게 기여했는데, CNN (SRCNN) 및 GAN (SRGAN)과 같은 방법이 사용되었다.
Problem Setting and Terminology
- Problem Definition: LR input에서 HR 이미지를 근사하는 SR 모델 개발
-
Image Quality Assessment (IQA): 인간의 주관적 판단 및 객관적 계산을 포함하여, full-reference, reduced-reference, no-reference 방법으로 분류된다.
Supervised Super-Resolution
SR Framework
- Pre-Upsampling Framework: 전통적인 upsampling 방식으로 LR 이미지를 확대한 후 DL network로 화질을 정제한다. (e.g., SRCNN).
- Post-Upsampling Framework: End-to-end DL 모델을 사용해 upsampling 한다.
- Progressive Upsampling Framework: CNNs을 cascade로 사용해 단계적으로 이미지를 정제한다.
- Iterative Up-and-Down Sampling: DBPN이나 SRFBN 모델과 같이 LR-HR 간 dependency를 더 잘 포착하는 방법.
Upsampling Methods
Interpolation-Based
Nearest-neighbor, bilinear, bicubic interpolation을 포함한다. DL 기반 방법이 등장하기 전까지 이미지 크기를 조정하는 데 사용되었다.
Learning-Based
Transposed convolution layer나 sub-pixel layer를 사용해 end-to-end로 모델을 학습한다
-
Transposed Convolution Layer (Deconvolution Layer): convolution output과 같은 크기의 feature map을 기반으로 input을 예측하여, 0을 삽입한 후 convolution을 수행해 이미지 크기를 키운다.
- 이미지 크기를 키우면서 패턴의 연결성을 유지하지만, 각 축에서 불균일하게 겹치는 부분이 생기면서 checkerboard 같은 결함을 초래할 수 있다.
-
Sub-Pixel Layer (Pixelshuffle): Convolution을 통해 다수의 채널을 생성하고 이것을 재구성한다.
- Input size가 $(h \times w \times c)$일 때, $s^2$배의 채널이 만들어진다. $s$는 scaling factor이다. Output size는 $(h \times w \times s^2c)$가 되고, 이것을 $(sh \times sw \times c)$로 재구성(shuffle)한다.
- Transposed convolution layer보다 receptive field가 커, 맥락과 현실적인 세부 사항을 더 반영할 수 있다. 하지만 receptive field의 분포가 균일하지 않아 블록 사이 경계 부근에서 결함이 발생할 수 있다.
Network Design
Residual Learning
- LR과 HR를 직접 매핑하는 것 대신 둘 간의 잔차(residual)에 집중하여 학습을 단순하게 한다. 변환 작업의 복잡도를 줄여준다.
- Input 이미지와 target 이미지 간 residual만 학습함으로써 모델이 세부적인 사항에 집중할 수 있고, 이것으로 성능이 향상될 뿐 아니라 수렴 속도도 빨라진다.
- Example: ResNet architecture는 residual block을 사용해 네트워크가 아주 깊어도 효과적으로 학습시킬 수 있다.
Recursive Learning
- 동일한 모듈을 반복적으로 적용하여 high-level feature를 캡쳐한다.
- feature를 반복적으로 정제하여 더 디테일하고 정확한 이미지를 reconstruct 하게끔 한다.
- Example: Deep Recursive Convolutional Network (DRCN)은 단일 convolutional layer를 여러 번 사용해 receptive field를 확장하면서도 파라미터 수를 크게 증가시키지 않는다.
Multi-Path Learning
- Local Multi-Path Learning
- 병렬적인 경로를 통해 feature를 추출하고, 이를 융함하여 더 나은 모델링을 가능하게 한다. 이미지의 다양한 측면을 동시에 캡쳐하는 데 도움이 된다.
- 각 경로는 각각 다른 규모나 유형의 feature에 집중할 수 있고, 이것을 결합해 전체적인 representation을 개선한다.
- Example: Multi-scale Residual Network (MSRN)은 다양한 커널 크기를 가진 multiple convolutional layer를 사용해 multi-scale feature를 캡쳐한다.
- Scale-Specific Multi-Path Learning
- 단일 네트워크 내에서 다양한 scaling factor에 대해 별도의 경로를 갖으면서도, 네트워크가 여러 scale을 더 효과적으로 처리할 수 있게 한다.
- Example: MDSR (Multi-Scale Deep Super-Resolution)은 대부분의 파라미터를 공유하지만, 다른 upscaling factor를 다루기 위해 scale-specific layer를 사용한다.
Dense Connections
- 각 레이어를 서로 feed forward 방식으로 연결해, gradient flow와 feature 재사용을 촉진한다. 이것으로 gradient가 이전 레이어로 직접 흐를 수 있게 하여 학습 효율을 높인다.
- feature를 재사용하게끔 하여 효율적이고 컴팩트한 네트워크를 만든다.
- Example: DenseNet은 각 레이어를 모든 레이어에 연결해 feature의 propagation을 촉진하여 gradient vanishing의 위험을 줄인다.
Group Convolution
- Input 채널을 그룹화하고, 각 그룹 내에서 convolution을 수행하여 계산 복잡도와 파라미터 수를 줄인다.
- 경량 모델에서 성능과 효율성을 균형 있게 가져가기 위해 사용된다.
- Example: Xception과 MobileNet은 depthwise separable convolution을 사용하여 파라미터와 계산량을 줄인다.
Pyramid Pooling
- 여러 scale에서 pooling을 해 global 및 local 맥락 정보를 파악한다. 이미지를 다양한 해상도로 이해하는 데 도움이 된다.
- Example: PSPNet (Pyramid Scene Parsing Network)은 pyramid pooling을 사용해 다양한 scale에서의 얻은 정보를 결합하여 feature representation을 향상시킨다.
Attention Mechanisms
- Channel Attention
- Feature 채널 간 상호의존성(interdependency)에 집중한다. 각 채널에 다른 weight를 주어 중요한 feature를 강조하고 덜 중요한 feature는 덜 반영한다.
- Example: Squeeze-and-Excitation Networks (SENet)은 spacial 차원에서 feature map을 squeeze하고 채널 별 feature를 재조정하는 excitation 연산을 한다.
- Spatial Attention
- feature의 공간적 위치에 집중한다. 다른 위치에 weight를 할당하여, 모델이 이미지에 관련된 영역에 집중할 수 있게 한다.
- Example: Convolutional Block Attention Module (CBAM)은 채널 및 공간 정보 관련 attention을 결합해 의미 있는 부분에 집중해 representation을 개선한다.
- Non-Local Attention
- 멀리 떨어진 픽셀 간 dependency를 파악한다. 이는 global context가 중요한 SR 작업에 특히 유용하다.
- Example: Non-local Neural Networks는 self-attention mechanism을 사용해 feature map 내 모든 위치 간 관계를 계산해 global context와 dependency를 캡쳐한다.
- Combined Attention
- 여러 가지 attention mechanism 방식을 결합해 각 유형의 강점을 활용할 수 있다. 예를 들어 channel attention과 spatial attention을 결합해 더욱 포괄적으로 해석 가능한 attention mechanism을 구현할 수 있다.
- Example: The Residual Channel Attention Network (RCAN) residual 네트워크 내에서 channel attention 모듈을 사용해 중요한 feature를 캡쳐하는 능력을 향상시켰다.
Learning Strategies
- Loss Functions: 초기에는 pixel-wise L2 loss를 사용했는데, 최근에는 content loss, adversarial loss, perceptual loss와 같은 더 복잡한 loss를 통합 사용하여 이미지의 품질을 향상시킨다.
- Training Techniques: curriculum learning, multi-supervision, progressive learning과 같은 기법을 사용해 학습 과정 및 모델 성능을 개선한다.
Unsupervised Super-Resolution
Unsupervised method는 페어링된 LR-HR dataset에 의존하지 않는다. 대신 adversarial training을 사용해 LR를 HR로 매핑하는 것을 생성 모델에 학습시킨다. 예를 들어 CycleGAN은 LR을 HR로, 또 그 역으로도 매핑함으로써 이미지 변환을 학습한다.
Domain-Specific Super-Resolution
Domain-specific method는 face SR, text SR, medical image SR과 같이 특정 응용 분야에 중점을 둔다. 도메인 지식을 활용해 특정 context에서의 SR 품질을 향상시킨다.
Set5, Set14, BSD100, Urban100 등 여러 benchmark dataset이 SR 모델 평가에 사용된다. 일반적인 metric으로는 Peak Signal-to-Noise Ratio (PSNR)와 Structural Similarity Index (SSIM)가 있다.
Metrics
PSNR은 널리 사용되나, 품질에 대한 사람의 인식과 잘 일치하지는 않는다. 한편 SSIM은 밝기, 대비, 구조 등을 고려해 이 점을 보완한다.
-
PSNR: 제일 보편적인 reconstruction quality 측정 metric이다. SR의 경우 최대 픽셀 값($L$)과 이미지 간 평균 제곱 오차(mean squared error; MSE)를 통해 PSNR을 정의한다.
\[PSNR=10\cdot\log_{10}\big({L^2\over{1\over N}\sum_{i=1}^N(I(i)-\hat{I}(i))^2}\big)\]
- $I(i)$와 $\hat{I}(i)$는 각각 원본 이미지와 생성된 이미지의 픽셀 값을 나타낸다. $N$은 총 픽셀 수이다.
-
SSIM: 밝기, 대비, 구조의 측면에서 이미지를 각각 비교하여 구조적 유사성을 측정한다. 인간의 시각 시스템(human visual system; HVS)이 자연스럽고 익숙하게 이미지 구조를 파악한다고 가정한다.
\[SSIM(I,\hat{I})={(2\mu_I\mu_{\hat{I}}+C_1)(2\sigma_{I\hat{I}}+C_2)\over(\mu_I^2+\mu_{\hat{I}}^2+C_1)(\sigma_I^2+\sigma_\hat{I}^2+C_2)}\]
- $\mu_I$와 $\mu_\hat{I}$은 각각 원본 이미지와 생성된 이미지의 평균 픽셀 값이다. $\sigma_I^2$와 $\sigma_\hat{I}^2$는 분산, $\sigma_{I\hat{I}}$는 $I$와 $\hat{I}$의 공분산이다. $C_1$와 $C_2$는 분모가 작은 경우를 대비해 계산의 안정성을 위해 사용되는 상수이다.
Challenges and Future Directions
- Scalability: 다양한 scale과 resolution을 효율적으로 처리할 수 있는 SR 모델 개발하기.
- Real-World Applications: 다양한 원인에 의해 해상도가 낮은 실제 이미지에서 잘 작동하도록 SR 모델 개선하기.
- Efficiency: 높은 성능을 유지하며 계산 복잡도와 메모리 샤용량 줄이기.
- Generality: 다양한 유형과 도메인의 이미지에서 일반화될 수 있는 SR 모델 개발하기.
- Perceptual Quality: 시각적으로 깔끔하고 결함이 없는 이미지를 생성하도록 모델 발전시키기.
Conclusion
이 survey paper는 supervised, unsupervised, domain-specific method 등으로 유형화하여 DL 기반의 SR 기술에 대해 심층적으로 검토한다. Benchmark dataset과 성능 평가 metric을 설명하고, SR 연구의 현재 상태에 대해 포괄적인 개요를 제공한다. 나아가 다양한 네트워크, upsampling 및 학습 기술을 살펴보고, 이 분야의 발전 방향을 제시한다.