Skip to content

DataScience-Lab-Yonsei/26-1_DSL_Modeling_NLP1

 
 

Repository files navigation

Is Attention Explainable?

DSL 26-1 Modeling — NLP Project
14기 구기현 · 14기 권나연 · 14기 어희정 · 15기 조유빈


Project Overview

딥러닝 모델이 발전하면서 모델의 블랙박스 문제를 해결하려는 노력이 함께 수반되고 있습니다.
특히 NLP에서 Attention은 모델이 어떤 단어에 주목하는지를 나타낸다는 점에서 자주 설명 근거로 사용됩니다.

본 프로젝트는 다음 질문에서 출발합니다:

NLP 모델의 Attention은 실제로 모델의 추론 근거를 설명할 수 있는가?

이를 검증하기 위해 SOP(Sentence Ordering Problem) 태스크를 선택했습니다.
SOP는 순서 이해가 모든 언어 이해의 전제조건이기에 높은 추론을 요구하며, 특히 수능영어 36~39번(순서배열·문장삽입)처럼 인간의 풀이 근거를 직접 수집·비교하기에 적합합니다.

방법: 동일한 태스크에 대해 모델의 Attention weight과 Gradient 기반 중요도(Jain & Wallace, 2019)를 추출하고, 두 설명의 일치도를 Kendall τ로 측정합니다. 그 결과를 LLM(ChatGPT·Gemini·Claude) 및 인간 피험자의 근거 단어와 비교합니다.


Pipeline

[Data 1: arXiv 400k]          [Data 2: CSAT 2017~2025]
        │                               │
   ft_arxiv.py                     ft_sn.py
        │                               │
   best_models/          ←── load ──   │
   (fine-tune 1)                        │
                                 best_models_ft2/
                                 (fine-tune 2)
                                        │
                                   test_sn.py
                                        │
                                  test_results/
단계 스크립트 입력 출력
기본 학습 ft_arxiv.py arXiv abstract 400k best_models/
수능 파인튜닝 ft_sn.py sn_dataset/ + best_models/ best_models_ft2/
수능 테스트 test_sn.py sn_dataset/ + best_models_ft2/ test_results/

학습 방식

두 문장 쌍 (s1, s2)을 입력받아 정순(0) / 역순(1) 을 예측하는 Binary Classification입니다.

[s1] [SEP] [s2]  →  EMBEDDING  →  ATTENTION  →  FNN  →  정순/역순

Gradient : 임베딩 값이 조금 변할 때 결과 확률에 영향을 미치는 정도
Attention : 학습된 어텐션 가중치 값

모델

모델 구조
BERT bert-base-uncased + Attention Layer + Classifier
BiLSTM Embedding + BiLSTM + Additive Attention + Classifier
CNN Embedding + Conv1D (kernel 1,3,5,7) + Attention + Classifier
Average Embedding + Projection + Attention + Classifier

데이터

Data 1 — arXiv Papers Abstract

  • 2016년 5월 이전 논문 요약 400,000개
  • split_logic3으로 논문 요약을 4개 청크로 분할 (담화 마커 기반 가중치)
  • Train / Val / Test : 1,846,272 / 102,656 / 102,656 쌍
  • Batch: 64 | LR: BERT 2e-5, BiLSTM/CNN 3e-5

Data 2 — 수능영어 기출 (sn_dataset/)

  • 교육청·평가원 영어 기출 2017~2025년 (JSON 60개)
  • Train / Val / Test : 9,016 / 1,012 / 1,012 쌍
  • Batch: 32 | LR: 1e-5 | BERT 하위 10개 레이어 + Embedding Freeze

Output / Evaluation

학습 정확도 (Test Accuracy)

모델 Base Fine-tune 1 (arXiv) Fine-tune 2 (수능)
BERT 0.509 0.813 0.843
BiLSTM 0.498 0.718 0.763
CNN 0.501 0.654 0.703

Attention vs Gradient 일치도 (Kendall τ)

모델 Kendall τ
BERT 0.1732
BiLSTM 0.1956
CNN 0.2116

τ 값이 전반적으로 낮음 → Attention과 Gradient의 일치도가 낮다는 것을 의미합니다.

수능 실전 정답률

모델 순서배열 (116문항) 문장삽입 (119문항)
BERT 60.3% (70/116) 47.9% (57/119)
BiLSTM 17.2% (20/116) 19.3% (23/119)
CNN 21.6% (25/116) 25.2% (30/119)

LLM 비교 (2025년 9월 37번 기준)

비교 대상 주요 근거 단어
ChatGPT math, confusion, notation, difficulty, recognition
Gemini not understood, professional mathematicians, complicated notation
Claude You would not be first, complicated notations, Put simply
BERT Gradient mathematics, mathematical, first, recognise, simply
BERT Attention to, that, the, a, are

Gradient가 LLM 및 인간의 근거 단어와 더 높은 일치도를 보임

결론

Sentence Ordering에서 Attention보다 Gradient가 더 유용한 설명 근거를 제공한다.
Attention은 모델 내부의 주목 단어를 상징할 수 있으나, Explainable한 근거로 직접 사용하기는 어렵다.


Repository Structure

nlp/
├── ft_arxiv.py              # arXiv 데이터 SOP 학습 → best_models/
├── ft_sn.py                 # 수능 데이터 파인튜닝 → best_models_ft2/
├── test_sn.py               # 수능 전체 JSON 테스트 → test_results/
│
├── sn_dataset/              # 수능영어 기출 JSON (2017~2025, 60개 파일)
│   ├── 2017/
│   ├── 2018/
│   │   └── ...
│   └── 2025/
│
├── best_models/             # arXiv 학습 가중치 (git 제외 권장)
│   ├── bert_sop_ft.pth
│   ├── paper_bilstm_sop_ft.pth
│   ├── paper_cnn_sop_ft.pth
│   ├── paper_avg_sop_ft.pth
│   └── experiment_results_ft.pkl
│
├── best_models_ft2/         # 수능 파인튜닝 가중치 + 시각화 (git 제외 권장)
│   ├── bert_suneung_ft2.pth
│   ├── bilstm_suneung_ft2.pth
│   ├── cnn_suneung_ft2.pth
│   ├── avg_suneung_ft2.pth
│   ├── fig1_kendall_tau.png
│   ├── fig2_attn_grad_scatter.png
│   ├── fig3_acc_pmr.png
│   ├── fig4_loss_curves.png
│   └── results.json
│
├── 문장삽입성능향상모델/       # 실험 2: DeBERTa-v3-base + Ranking Head
├── 순서배열성능향상모델/       # 실험 3: RoBERTa + FusionTransformer
└── llm_prompt.txt           # LLM 비교 실험 프롬프트 (ChatGPT / Gemini / Claude)

Other Experiments (실험 2, 3)

실험 2 — DeBERTa-v3-base (문장삽입성능향상모델/)

  • 문장삽입 태스크를 Multiple Choice Ranking 방식으로 학습
  • arXiv Pairwise Acc: 91.47% / 수능 FT: 80.74%
  • 수능 PMR: Q38(문장삽입 2점) 95.0%, Q39(3점) 91.5%

실험 3 — RoBERTa + FusionTransformer (순서배열성능향상모델/)

  • Discourse-aware Fusion (Expansion·Contingency·Comparison·Temporal 관계 파싱)
  • arXiv Pairwise Acc: 88.51% / 수능 FT: 78.87%
  • 수능 PMR: Q36(순서배열 2점) 87.9%, Q37(3점) 81.0%

Usage

# 1. arXiv 기본 학습
python ft_arxiv.py

# 2. 수능 파인튜닝
python ft_sn.py

# 3. 수능 문제 테스트
python test_sn.py

ft_arxiv.py 실행 시 arxiv-metadata-oai-snapshot.json이 같은 디렉토리에 필요합니다.
모델 가중치(.pth)와 대용량 데이터 파일은 .gitignore에 추가하는 것을 권장합니다.

Requirements

torch
transformers
scikit-learn
scipy
nltk
tqdm
matplotlib
numpy

References

  • Jain, S., & Wallace, B. C. (2019). Attention is not Explanation. NAACL-HLT 2019. [paper]
  • Devlin, J., et al. (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. NAACL-HLT 2019. [paper]
  • He, P., et al. (2021). DeBERTa: Decoding-enhanced BERT with Disentangled Attention. ICLR 2021. [paper]
  • Liu, Y., et al. (2019). RoBERTa: A Robustly Optimized BERT Pretraining Approach. [paper]
  • Clement, C. B., et al. (2019). On the Use of ArXiv as a Dataset. [paper]

About

수능영어 순서배열 태스크(SOP)를 통해 NLP 모델의 Attention이 설명력을 가지는지 검증하고, Gradient·LLM·인간 피험자 결과와 비교 분석한 프로젝트

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • Python 70.8%
  • Jupyter Notebook 29.2%