TIL
  • Main
  • TIL : ML
    • AI News
      • AI-powered coding, free of charge with Colab
    • Paper
      • Retrieval-augmented generation for knowledge-intensive nlp tasks
        • reference 정리
      • Sequence to Sequence
    • Generative AI
      • LLM
        • 기본 개념
    • Boostcamp
      • Daily Report
        • 2021
          • 09
            • week4
            • week5
          • 10
            • week1
            • week2
            • week3
            • week4
          • 11
            • week1
            • week2
            • week3
            • week4
            • week5
          • 12
            • week1
            • week2
            • week3
      • Final Project
        • 프로젝트 기획
          • 🌟최종 프로젝트 기획
          • 최종 프로젝트 Version
          • 아이디어 수집
          • 욕설, 혐오발언 감지
          • 라이브 커머스 레포팅 프로젝트
        • 프로젝트 진행
          • week1
          • week2
          • week3
      • Competition
        • 1. [NLP] 문장 내 개체간 관계 추출
          • Day1 (9.27, 월)
          • Day2-3 (9.28~29, 화~수)
          • Day4 (9.30, 목)
          • Day5 (10.1, 금)
          • Day6~7 (10.2~3, 토~일)
          • Day8 (10.4, 월)
          • Day9 (10.5, 화)
          • Day10 (10.6, 수)
          • Day 11 (10.7 목)
        • 2. [NLP] MRC 프로젝트
          • Day1 (10.25, 월)
          • Day2 (10.26, 화)
          • Day3 (10.27, 수)
          • Day4-5 (10.28-29, 목-금)
          • Day6 (11.1, 월)
          • Day7 (11.2, 화)
          • Day8 (11.3, 수)
          • Day9 (11.4, 목)
        • 🔨3. [NLP] 데이터 제작
          • Day1
        • 🔨4. [공통] 모델 경량화
      • [U Stage] - DL basic
        • (01강) 딥러닝 기본 용어 설명 - Historical Review
        • (02강) 뉴럴 네트워크 - MLP (Multi-Layer Perceptron)
        • (03강) Optimization
        • 🔨(04강) Convolution은 무엇인가?
        • 🔨(05강) Modern CNN - 1x1 convolution의 중요성
        • 🔨(06강) Computer Vision Applications
        • (07강) Sequential Models - RNN
        • (08강) Sequential Models - Transformer
        • Page 2
      • [U Stage] - PyTorch
        • (01강) Introduction to PyTorch
        • (02강) PyTorch Basics
        • (03강) PyTorch 프로젝트 구조 이해하기
        • (04강) AutoGrad & Optimizer
        • (05강) Dataset & Dataloader
        • (06강) 모델 불러오기
        • (07강) Monitoring tools for PyTorch
        • (08강) Multi-GPU 학습
        • (09강) Hyperparameter Tuning
        • (10강) PyTorch Troubleshooting
      • [U Stage] - NLP
        • (01강) Introduction to NLP, Bag-of-Words
        • (02강) Word Embedding
        • (03강) Recurrent Neural Network and Language Modeling
        • (04강) LSTM and GRU
        • (05강) Sequence to Sequence with Attention
        • (06강) Beam Search and BLEU score
        • (07-08강) Transformer
        • (09강) Self-supervised Pre-training Models
      • [P Stage] - KLUE
        • (1강) 인공지능과 자연어 처리
        • (2강) 자연어의 전처리
        • (3강) BERT 언어모델 소개
        • (4강) 한국어 BERT 언어 모델 학습
        • (5강) BERT 기반 단일 문장 분류 모델 학습
        • (6강) BERT 기반 두 문장 관계 분류 모델 학습
        • (7강) BERT 언어모델 기반의 문장 토큰 분류
        • 오피스아워 (9.30, 목)
        • (8강) GPT 언어 모델
        • (9강) GPT 언어모델 기반의 자연어 생성
        • (10강) 최신 자연어처리 연구
      • [P Stage] - MRC
        • Before Study
        • (1강) MRC Intro & Python Basics
        • (2강) Extraction-based MRC
        • (3강) Generation-based MRC
        • (4강) Passage Retrieval - Sparse Embedding
        • (5강) Passage Retrieval - Dense Embedding
        • 오피스아워
        • (6강) Scaling up with FAISS
        • (7강) Linking MRC and Retrieval
        • (8강) Reducing Training Bias
        • (9강) Closed-book QA with T5
        • (10강) QA with Phrase Retrieval
        • 마스터클래스
      • [P Stage] - 데이터제작(NLP)
        • (1강) 데이터 제작의 A to Z
        • (2강) 자연어처리 데이터 기초
        • (3강) 자연어처리 데이터 소개 1
        • (4강) 자연어처리 데이터 소개 2
        • (5강) 원시 데이터의 수집과 가공
        • 오피스아워 (11.10, 수)
        • (6강) 데이터 구축 작업 설계
        • (7강) 데이터 구축 가이드라인 작성 기초
        • (8강) 관계 추출 과제의 이해
        • (9강) 관계 추출 관련 논문 읽기
        • (10강) 관계 추출 데이터 구축 실습
      • [P Stage] - 모델 최적화
        • (1강) 최적화 소개 및 강의 개요
        • (2강) 대회 및 데이터셋 소개
        • (3강) 작은 모델, 좋은 파라미터 찾기: AutoML 이론
        • 🔨(4강) 작은 모델, 좋은 파라미터 찾기: AutoML 실습
        • (5강) 작은 모델, 좋은 파라미터 찾기: Data Augmentation & AutoML 결과 분석
        • 🔨오피스아워 -Baseline 코드에 모듈 작성하기(신종선 멘토님)
      • [P Stage] - Product Serving
        • Part 1: Product Serving 개론
          • 1.1 강의 진행 방식
          • 1.2 MLOps 개론
          • 1.3 Model Serving
          • 1.4 머신러닝 프로젝트 라이프 사이클
        • Part 2: 프로토타입부터 점진적으로 개선하기
          • 2.1 프로토타이핑 - Notebook 베이스(Voila)
          • 2.2 프로토타이핑 - 웹 서비스 형태(Streamlit)
          • 2.3 Linux & Shell Command
          • 2.4 Cloud
          • 2.5 Github Action을 활용한 CI/CD
        • Part 3: 더 완성화된 제품으로
          • 3.1.1 FastAPI
          • 3.1.2 Fast API
          • 3.1.3 Fast API
          • 3.2 Docker
          • 3.3 Logging
          • 3.4 MLFlow
        • Part 4: 심화 소재
          • 4.1 BentoML
          • 4.2 Airflow
          • 4.3 머신러닝 디자인 패턴
          • 4.4 앞으로 더 공부하면 좋을 내용
      • 특강
        • (특강) 김상훈 - 캐글 그랜드마스터의 노하우 대방출
        • (특강) 이활석 - 서비스 향 AI 모델 개발하기
        • (특강) 구종만 - AI + ML과 Quant Trading
        • (특강) 문지형 - 내가 만든 AI 모델은 합법일까, 불법일까
        • (특강) 이준엽 - Full Stack ML Engineer
        • (특강) 박은정 - AI 시대의 커리어 빌딩
        • (특강) 오혜연 - AI Ethics
    • Competition
      • (DACON)한국어 문장 관계 분류 경진대회
        • Day1(2.14, 월)
        • Day2(2.15, 화)
        • Day3(2.16, 수)
        • Day4(2.17, 목)
      • 2021 인공지능 데이터 활용 경진대회
        • 역량평가
          • Day1 (9.28, 화)
          • Day2 (9.29, 수)
          • Day3 (9.30, 목)
        • 예선
          • Data 분석
          • NSML
          • What We Have Done?
    • ETC
      • 인터뷰 대비
        • Computer Science
        • ML/DL
      • Poetry로 dependency 관리
        • window에서 설치하기
      • code block
      • 공부할 것 임시보관
      • Transformer to T5
      • Hugging Face Tutorial
        • Ch1. Transformer models
        • Ch2. Using Transformers
        • Ch3. Fine-tuning a model with the Trainer API
      • KLUE
      • Pandas
  • TIL : Ops
    • AWS
      • SageMaker
  • TIL : Computer (CS)
    • Error
      • TextEncodeInput must be Union[TextInputSequence, Tuple[InputSequence, InputSequence]]
    • Algorithm
      • Theory
      • Programmers
        • 기능개발
    • ETC
      • Github 커밋 히스토리 삭제
Powered by GitBook
On this page
  • 0. Setup
  • 1. Introduction
  • 2. Natural Language Processing (NLP)
  • 3. Transformers, what can they do?
  • 3.1. Zero-shot classification
  • 3.2. Text generation
  • 3.3. Using any model from the Hub in a pipeline
  • 3.4. Mask filling
  • 3.5. Named entity recognition
  • 3.6. Question Answering
  • 3.7. Summarization
  • 3.8. Translation
  • 4. How do Transformers work?
  • 4.1. Transformers are language models
  • 4.2. Transfer Learning (전이학)
  • 4.3. General architecture
  • 4.4. Attention layers
  • 4.5. The original architecture
  • 4.6. Architectures vs. checkpoints
  • 5. Encoder models
  • 6. Decoder models
  • 7. Sequence-to-sequence models
  • 8. Bias and limitations
  • 9. Summary

Was this helpful?

  1. TIL : ML
  2. ETC
  3. Hugging Face Tutorial

Ch1. Transformer models

PreviousHugging Face TutorialNextCh2. Using Transformers

Last updated 3 years ago

Was this helpful?

0. Setup

!pip install transformers # light version
!pip install transformers[sentencepiece] # ✔ development version 
import transformers

1. Introduction

이 코스를 통해 Hugging Face에서 Transformers, Datasets, Tokenizers, Accelerate, Hugging Face Hub 의 사용법을 배울 수 있다.

처음 과정인 Ch. 1~4을 통해서 hugging face hub로 부터 트랜스포머 모델을 가져오고 사용하는 법에 대해서 배울 수 있게 된다.

  • How to pipline function to solve NLP tasks such as text generation and classification

  • About the Transformer architecture

  • How to distinguish between encoder, decoder and encdoer-decoder architectures and use cases

2. Natural Language Processing (NLP)

NLP는 사람의 언어와 연관된 모든 것들을 이해하는 기계학습과 언어학의 분야이다. 단순히 단어를 이해하는 것에 그치지 않고 문장이 내포하는 의미까지 파악하고자 하는 목표를 가지고 있다.

  • Classifying whole sentences

  • Classifying each word in a sentences

  • Generating text content

  • Extracting an answer from a text

  • Generating a new sentence from an input text

위와 같이 다양한 Task를 다루며, 음성인식과 Computer Vision에서 그림에 대한 설명글을 만드는 등 활용이 가능하다.

컴퓨터는 사람과 정보를 수집하는 방법이 다르다. 예를 들어 'I am hungry'와 'I am sad'라는 두 문장이 의미하는 유사점을 쉽게 알 수 있지만, ML 모델에게는 매우 어려운 일이다. 이처럼 복잡한 언어를 학습하기 위한 모델을 알아볼 것이다.

3. Transformers, what can they do?

이미 다양한 분야와 회사에서 Hugging Face와 Transformer models를 사용하고 있다. Transformers library는 직접 만들고 나눌 수 있다.

pipeline

It connects a model with its necessary preprocessing and postprocessing steps, allowing us to directly input any text and get an intelligible answer

pipeline을 통해 가져온 모델로 여러 Task를 확인해보기로 한다.

  • 위와 같이 감정분석 모델을 가져와서 input을 주는 것만으로 그 결과를 알 수 있다.

  • 모델을 지정해 주지 않으면 default 모델 (distilbert-base-uncased-finetuned-sst-2-english)을 사용한다.

  • 해당 모델은 classifier 객체를 생성하게 되면 다운로드되어 메모리에 적재된다.

pipeline을 통해 진행되는 과정은 아래 3단계를 거친다.

  1. The text is preprocessed into a format the model can understand.

  2. The preprocessed inputs are passed to the model.

  3. The predictions of the model are post-processed, so you can make sense of them.

3.1. Zero-shot classification

문장 분류 Task

3.2. Text generation

문장 생성 Task

3.3. Using any model from the Hub in a pipeline

  • HuggingFace Hub에 있는 모델을 가져와 학습하기

  • num_return_sequence 와 max_length parameter 사용해보기

    • num_return_sequence : 문장 갯

    • max_length : 문장의 최대 길이

3.4. Mask filling

  • 빈 공간 문자(<MASK>, [MASK]) 채우기

  • top_k : 출력할 갯수

3.5. Named entity recognition

  • 고유명사의 분류 (이름, 장소, 단체)

3.6. Question Answering

  • 질문과 문장을 주고 응답을 찾아내는 Task

3.7. Summarization

from transformers import pipeline

summarizer = pipeline("summarization")
summarizer("""
    America has changed dramatically during recent years. Not only has the number of 
    graduates in traditional engineering disciplines such as mechanical, civil, 
    electrical, chemical, and aeronautical engineering declined, but in most of 
    the premier American universities engineering curricula now concentrate on 
    and encourage largely the study of engineering science. As a result, there 
    are declining offerings in engineering subjects dealing with infrastructure, 
    the environment, and related issues, and greater concentration on high 
    technology subjects, largely supporting increasingly complex scientific 
    developments. While the latter is important, it should not be at the expense 
    of more traditional engineering.

    Rapidly developing economies such as China and India, as well as other 
    industrial countries in Europe and Asia, continue to encourage and advance 
    the teaching of engineering. Both China and India, respectively, graduate 
    six and eight times as many traditional engineers as does the United States. 
    Other industrial countries at minimum maintain their output, while America 
    suffers an increasingly serious decline in the number of engineering graduates 
    and a lack of well-educated engineers.
""")
  • 문장요약

3.8. Translation

from transformers import pipeline

translator = pipeline("translation", model="Helsinki-NLP/opus-mt-fr-en")
translator("Ce cours est produit par Hugging Face.")
[{'translation_text': 'This course is produced by Hugging Face.'}]
  • 번역 문제

4. How do Transformers work?

4.1. Transformers are language models

Language Model이란 주어진 단어들 다음에 나올 단어를 예측하는 Task를 의미한다.

Unfortunately, training a model, especially a large one, requires a large amount of data. This becomes very costly in terms of time and compute resources. 큰 모델을 학습하게 되면 수많은 양의 데이터가 필요하게 된다.

매 학습때마다, 새로운 데이터를 학습시킨다면 어마어마한 손해일 것이다.

4.2. Transfer Learning (전이학)

A Task에 대해 학습한 Model A 를 Task B 에 적용하는 것. 이렇게 할 경우 더 좋은 성능을 가지는 것이 확인되었다.

Fine-tuning, on the other hand, is the training done after a model has been pretrained. To perform fine-tuning, you first acquire a pretrained language model, then perform additional training with a dataset specific to your task

Fine-Tuning 하게 되면, 결과적으로 적은시간, 적은 리소스, 적은 데이터로도 충분히 학습이 가능하고 또한 여러 hyperparameter로 다양한 테스트가 가능하게 한다.

4.3. General architecture

Transformer의 기본구조는 Boostcamp - [U Stage] NLP - (07-08강) Transformer에 정리해 두었으니 해당 내용을 참고하기로 한다.

우선 Transformer는 Encoder와 Decoder로 나뉘게 되는데 Input에 대한 data를 Encoder에서 가공하고 이 정보를 Decoder로 보내 Output Data를 생성해 내도록 나누어져 있다.

4.4. Attention layers

마찬가지로 Boostcamp에 정리가 잘 되어있으니 해당 내용을 참고하기로 하자.

Attention은 Seq to Seq모델에서 생기는 bottle neck 문제점 등을 해소할 수 있는 방법으로 소개 되었다. Transformer의 경우 Seq to Seq에서 RNN 부분을 사용하지 않고 Attention만을 사용하여 모델을 만들었고, 이 기법이 성능 향상에 큰 역할을 하였다.

4.5. The original architecture

4.6. Architectures vs. checkpoints

  • Architecture This is the skeleton of the model - the definition of each layer and each operation that happens within the model.

  • Checkpoints These are the weights that will be loaded in a given architecture.

  • Model This is an umbrella term that isn't as precise as "architecture" or "checkpoint": it can mean both.

예를 들어, BERT는 Architecture이고, bert-base-cased는 checkpoint이다.

5. Encoder models

Transformer의 Encoder부분만으로 만들어진 모델이다. 대표적으로 BERT모델이 있다. 이런 Encoder모델의 특징에 대해 다음과 같이 나열한다.

  • Bi-directional : 양방향성을 포함하여 문맥의 흐름에 대해 더 잘 파악한다.

  • Good at extracting meaningful information

  • Sequence classification, Question Answering, masked language modeling등에서 좋은 성능을 내고 있다.

  • NLU : Natural Language Understanding

  • BERT, RoBERTa, ALBERT

문맥을 이해하는 성능이 좋은 모델이라고 생각된다.

6. Decoder models

Encoder model이 Transformer에서 Encoder부분만 사용한 것이라면, Decoder model은 Transformer에서 Decoder부분만을 사용한 모델이다. 대표적으로 GPT 모델이 있다.

  • Great at causal tasks: generating sequences

    • Guessing the next word in a sentence

  • NLG: Natural Language Generation

  • GPT-2, GPT Neo

7. Sequence-to-sequence models

Encoder-Decoder models(=seq-to-seq models) 는 Transformer의 Encoder와 Decoder를 모두 사용하는 모델들이다. summarization, translation, or generative question answering 등과 같이 주어진 문장에 대해 새로운 문장을 만드는 것에서 좋은 성능을 낸다.

  • Sequence to Sequence Tasks: many to many (Translations, Summarization)

  • Weights are not necessarily shared across the encoder and decoder

  • input distribution different from output distribution

  • BART, mBART, Marian, T5

8. Bias and limitations

Pre-Trained 모델은 많은 데이터를 긁어오다보니 좋지않은 데이터도 첨가되어 있다는 한계가 있음을 알고 있어야 한다.

from transformers import pipeline

unmasker = pipeline("fill-mask", model="bert-base-uncased")
result = unmasker("This man works as a [MASK].")
print([r["token_str"] for r in result])

result = unmasker("This woman works as a [MASK].")
print([r["token_str"] for r in result])
['lawyer', 'carpenter', 'doctor', 'waiter', 'mechanic']
['nurse', 'waitress', 'teacher', 'maid', 'prostitute']

9. Summary

위 예시의 경우 성별에 따라 그 성별이 많이 분포한 직업을 나열하고 있음을 볼 수 있다. 이는 BERT가 믿을만한 데이터 and 의 데이터로 학습하였기 때문이다.

English Wikipedia
BookCorpus
History of Transformer Model
LogoSetup - Hugging Face Coursehuggingface