DeepLearning
AutoModel 과 기타 모델 호출 형태
꼬꼬마코더
2024. 10. 31. 12:03
728x90
- 의도: klue/roberta-base라는 모델을 AutoModel을 사용해 불러오고 있습니다.
- 용도: 이 부분은 roberta-base 모델을 일반적인 사전 훈련된 형태로 불러오는 데 사용됩니다.
from transformers import AutoModel
model_id = 'klue/roberta-base'
model = AutoModel.from_pretrained(model_id)
RobertaModel(
(embeddings): RobertaEmbeddings(
(word_embeddings): Embedding(32000, 768, padding_idx=1)
(position_embeddings): Embedding(514, 768, padding_idx=1)
(token_type_embeddings): Embedding(1, 768)
(LayerNorm): LayerNorm((768,), eps=1e-05, elementwise_affine=True)
(dropout): Dropout(p=0.1, inplace=False)
)
(encoder): RobertaEncoder(
(layer): ModuleList(
(0-11): 12 x RobertaLayer(
(attention): RobertaAttention(
(self): RobertaSelfAttention(
(query): Linear(in_features=768, out_features=768, bias=True)
(key): Linear(in_features=768, out_features=768, bias=True)
(value): Linear(in_features=768, out_features=768, bias=True)
(dropout): Dropout(p=0.1, inplace=False)
)
(output): RobertaSelfOutput(
(dense): Linear(in_features=768, out_features=768, bias=True)
(LayerNorm): LayerNorm((768,), eps=1e-05, elementwise_affine=True)
(dropout): Dropout(p=0.1, inplace=False)
)
)
(intermediate): RobertaIntermediate(
(dense): Linear(in_features=768, out_features=3072, bias=True)
(intermediate_act_fn): GELUActivation()
)
(output): RobertaOutput(
(dense): Linear(in_features=3072, out_features=768, bias=True)
(LayerNorm): LayerNorm((768,), eps=1e-05, elementwise_affine=True)
(dropout): Dropout(p=0.1, inplace=False)
)
)
)
)
(pooler): RobertaPooler(
(dense): Linear(in_features=768, out_features=768, bias=True)
(activation): Tanh()
)
)
- 의도: SamLowe/roberta-base-go_emotions라는 감정 분류용 모델을 AutoModelForSequenceClassification을 사용해 불러옵니다.
- 용도: 이 부분은 roberta-base 기반 모델을 불러오며, 감정 분류(Sequence Classification) 작업에 적합한 구조로 사용됩니다.
from transformers import AutoModelForSequenceClassification
model_id = 'SamLowe/roberta-base-go_emotions'
classification_model = AutoModelForSequenceClassification.from_pretrained(model_id)
RobertaForSequenceClassification(
(roberta): RobertaModel(
(embeddings): RobertaEmbeddings(
(word_embeddings): Embedding(50265, 768, padding_idx=1)
(position_embeddings): Embedding(514, 768, padding_idx=1)
(token_type_embeddings): Embedding(1, 768)
(LayerNorm): LayerNorm((768,), eps=1e-05, elementwise_affine=True)
(dropout): Dropout(p=0.1, inplace=False)
)
(encoder): RobertaEncoder(
(layer): ModuleList(
(0-11): 12 x RobertaLayer(
(attention): RobertaAttention(
(self): RobertaSelfAttention(
(query): Linear(in_features=768, out_features=768, bias=True)
(key): Linear(in_features=768, out_features=768, bias=True)
(value): Linear(in_features=768, out_features=768, bias=True)
(dropout): Dropout(p=0.1, inplace=False)
)
(output): RobertaSelfOutput(
(dense): Linear(in_features=768, out_features=768, bias=True)
(LayerNorm): LayerNorm((768,), eps=1e-05, elementwise_affine=True)
(dropout): Dropout(p=0.1, inplace=False)
)
)
(intermediate): RobertaIntermediate(
(dense): Linear(in_features=768, out_features=3072, bias=True)
(intermediate_act_fn): GELUActivation()
)
(output): RobertaOutput(
(dense): Linear(in_features=3072, out_features=768, bias=True)
(LayerNorm): LayerNorm((768,), eps=1e-05, elementwise_affine=True)
(dropout): Dropout(p=0.1, inplace=False)
)
)
)
)
)
(classifier): RobertaClassificationHead(
(dense): Linear(in_features=768, out_features=768, bias=True)
(dropout): Dropout(p=0.1, inplace=False)
(out_proj): Linear(in_features=768, out_features=28, bias=True)
)
)
AutoModel과 AutoModelForSequenceClassification의 차이점은 출력 계층과 추가적인 레이어가 있는지에 따라 결정됩니다. 두 가지 경우 모두 Roberta 모델 구조를 사용하지만, 구조상 추가된 Pooler 및 Classification 헤드로 인해 다르게 사용됩니다.
주요 차이점
AutoModel의 출력 구조AutoModel은 사전 훈련된 모델 자체만을 불러오며, 주로 특성 추출(embedding) 목적으로 사용됩니다.- 마지막 출력에는
pooler레이어가 포함되며, 이를 통해 토큰 임베딩을 문장 단위의 하나의 벡터로 축소합니다. - 구성 요소:
(pooler): RobertaPooler( (dense): Linear(in_features=768, out_features=768, bias=True) (activation): Tanh() ) pooler는 입력 문장의 첫 번째[CLS]토큰을 768차원의 벡터로 변환하고Tanh활성화 함수를 적용하여 최종 문장 표현을 만듭니다.- 이 벡터는 직접 분류를 위한 용도는 아니며, 보통 추가적인 분류 헤드가 필요합니다.
AutoModelForSequenceClassification의 출력 구조AutoModelForSequenceClassification는 문장 분류 작업에 맞춰 추가적인classifier헤드를 포함합니다.- 구성 요소:
(classifier): RobertaClassificationHead( (dense): Linear(in_features=768, out_features=768, bias=True) (dropout): Dropout(p=0.1, inplace=False) (out_proj): Linear(in_features=768, out_features=28, bias=True) ) classifier헤드는 최종 문장 표현(pooler의 출력)을 입력받아, 분류 작업을 수행합니다. 이 과정에서:- Dense Layer를 통해 비선형 변환을 수행하고,
- Dropout으로 과적합을 방지하며,
- Output Projection Layer (
out_proj)에서 28개의 분류 클래스 중 하나로 예측을 제공합니다.
- 이 추가적인 분류 계층이 있어, 분류 과제에 맞춘 결과를 반환합니다.
요약
AutoModel은 문장 표현만을 제공하고 분류 기능은 없습니다. 따라서 추가적인 분류 계층을 사용자 정의로 추가해야 분류 작업이 가능합니다.AutoModelForSequenceClassification는 문장 표현을 받아 분류 결과를 출력하는 분류 헤드가 포함되어 있으며, 바로 분류 작업에 사용할 수 있습니다.
AutoModelForSequenceClassification에서는 pooler 레이어가 필요하지 않기 때문에 포함되지 않습니다. 그 이유는 문장 분류 작업에 필요한 최종 문장 표현을 만드는 과정이 pooler 없이도 충분하기 때문입니다. 여기서 각 토큰의 표현을 활용하거나 [CLS] 토큰의 임베딩을 바로 사용하는 방식으로 분류 작업을 수행할 수 있습니다.
구체적인 이유
pooler의 역할과 불필요성:pooler는 주로AutoModel에서 전체 문장 표현을 768차원으로 압축하기 위해 사용됩니다. 이 과정에서[CLS]토큰을 통과시키고Tanh활성화 함수를 적용합니다.AutoModelForSequenceClassification에서는[CLS]토큰의 출력 임베딩을 그대로 사용해classifier헤드에 입력으로 주기 때문에pooler레이어가 필요하지 않습니다.
- 분류 작업에서의 최적화:
AutoModelForSequenceClassification은 분류 작업에 초점을 맞춘 모델이므로, 최종 출력에서 바로classifier헤드를 통해 분류를 수행합니다.pooler의 추가적인 비선형 변환(Tanh등)이 오히려 분류 성능에 불필요한 영향을 줄 수 있어 제외되었습니다.
- 단순화와 효율성:
pooler를 거치지 않고 바로classifier레이어로 연결하면, 학습 속도와 메모리 효율성이 증가합니다. 이는 대규모 모델을 학습할 때 더 유리하며,AutoModelForSequenceClassification이 더욱 빠르고 간단하게 분류 작업을 수행하도록 돕습니다.
요약
AutoModelForSequenceClassification에서는 분류 작업에 직접 필요한 classifier 헤드만 포함하며, pooler가 없는 이유는 문장 표현을 추가 변환 없이 바로 분류 작업에 사용하기 위해서입니다.