반응형
블로그 이미지
개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들을 접할 기회가 많이 있습니다. 미국의 IT 프로젝트에서 사용되는 툴들에 대해 많은 분들과 정보를 공유하고 싶습니다.
솔웅

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리


반응형

https://huggingface.co/learn/nlp-course/chapter2/2?fw=pt

 

Behind the pipeline - Hugging Face NLP Course

This is the first section where the content is slightly different depending on whether you use PyTorch or TensorFlow. Toggle the switch on top of the title to select the platform you prefer! Let’s start with a complete example, taking a look at what happ

huggingface.co

 

Behind the pipeline

This is the first section where the content is slightly different depending on whether you use PyTorch or TensorFlow. Toggle the switch on top of the title to select the platform you prefer!

 

PyTorch를 사용하는지, TensorFlow를 사용하는지에 따라 내용이 조금씩 달라지는 첫 번째 섹션입니다. 제목 상단의 스위치를 전환하여 원하는 플랫폼을 선택하세요!

 

https://youtu.be/1pedAIvTWXk?si=qXNz-TvLKCLZEIsZ

 

 

Let’s start with a complete example, taking a look at what happened behind the scenes when we executed the following code in Chapter 1:

 

완전한 예제부터 시작해 1장에서 다음 코드를 실행했을 때 뒤에서 무슨 일이 일어났는지 살펴보겠습니다.

 

from transformers import pipeline

classifier = pipeline("sentiment-analysis")
classifier(
    [
        "I've been waiting for a HuggingFace course my whole life.",
        "I hate this so much!",
    ]
)

 

이 코드는 Hugging Face Transformers 라이브러리를 사용하여 감정 분석(sentiment analysis)을 수행하는 예제입니다.

이 코드는 두 개의 문장에 대해 감정 분석을 수행합니다. 생성된 'sentiment-analysis' 파이프라인은 입력된 각 문장의 감정을 판별하고, 결과를 리스트로 반환합니다. 출력된 결과는 입력된 각 문장에 대한 감정에 대한 정보를 담고 있습니다.

주의: 결과는 확률값으로 나타나며, 주어진 문장이 긍정적인 감정, 부정적인 감정, 혹은 중립적인 감정을 나타낼 확률을 표시합니다. 결과의 형식은 리스트 안에 딕셔너리 형태로 주어집니다.

 

and obtained: 그리고 얻은 것 :

[{'label': 'POSITIVE', 'score': 0.9598047137260437},
 {'label': 'NEGATIVE', 'score': 0.9994558095932007}]

 

CoLab 실행 결과

 

 

* sentiment-analysis 파이프라인의 디폴트 모델은 distilbert-base-uncased-finetuned-sst-2-english 임 위 링크를 클릭하면 해당 모델을 설명하는 페이지로 이동 할 수 있음.

 

https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english

 

distilbert-base-uncased-finetuned-sst-2-english · Hugging Face

🔥 ANDRYHA/FakeNewsClassifier 📚 CK42/sentiment-model-comparison ⌨️ EnzoBustos/IC-2022-Classificacao-de-Dados-Financeiros 📚 abrar-adnan/speech-analyzer 🏆 CodyJiang/Finetuning-Sentiment-Analysis-App 🛡️ anonymous8/Rapid-Textual-Adversarial

huggingface.co

 

As we saw in Chapter 1, this pipeline groups together three steps: preprocessing, passing the inputs through the model, and postprocessing:

 

1장에서 본 것처럼 이 파이프라인은 전처리, 모델을 통해 입력 전달, 후처리의 세 단계로 그룹화됩니다.

 

Let’s quickly go over each of these.

 

각 항목을 빠르게 살펴보겠습니다.

 

 

Preprocessing with a tokenizer

 

Like other neural networks, Transformer models can’t process raw text directly, so the first step of our pipeline is to convert the text inputs into numbers that the model can make sense of. To do this we use a tokenizer, which will be responsible for:

 

다른 신경망과 마찬가지로 Transformer 모델은 원시 텍스트를 직접 처리할 수 없으므로 파이프라인의 첫 번째 단계는 텍스트 입력을 모델이 이해할 수 있는 숫자로 변환하는 것입니다. 이를 위해 우리는 다음을 담당하는 토크나이저를 사용합니다.

 

  • Splitting the input into words, subwords, or symbols (like punctuation) that are called tokens

  • 입력을 토큰이라고 하는 단어, 하위 단어 또는 기호(구두점 등)로 분할

  • Mapping each token to an integer

  • 각 토큰을 정수로 매핑

  • Adding additional inputs that may be useful to the model

  • 모델에 유용할 수 있는 추가 입력 추가

All this preprocessing needs to be done in exactly the same way as when the model was pretrained, so we first need to download that information from the Model Hub. To do this, we use the AutoTokenizer class and its from_pretrained() method. Using the checkpoint name of our model, it will automatically fetch the data associated with the model’s tokenizer and cache it (so it’s only downloaded the first time you run the code below).

 

이 모든 전처리는 모델이 사전 훈련되었을 때와 정확히 동일한 방식으로 수행되어야 하므로 먼저 모델 허브에서 해당 정보를 다운로드해야 합니다. 이를 위해 AutoTokenizer 클래스와 해당 from_pretrained() 메서드를 사용합니다. 모델의 체크포인트 이름을 사용하면 모델의 토크나이저와 관련된 데이터를 자동으로 가져와 캐시합니다(따라서 아래 코드를 처음 실행할 때만 다운로드됩니다).

Since the default checkpoint of the sentiment-analysis pipeline is distilbert-base-uncased-finetuned-sst-2-english (you can see its model card here), we run the following:

 

감정 분석 파이프라인의 기본 체크포인트는 distilbert-base-uncased-finetuned-sst-2-english(여기서 해당 모델 카드를 볼 수 있음)이므로 다음을 실행합니다.

 

from transformers import AutoTokenizer

checkpoint = "distilbert-base-uncased-finetuned-sst-2-english"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)

 

이 코드는 Hugging Face Transformers 라이브러리를 사용하여 사전 훈련된 모델의 토크나이저를 로드하는 예제입니다.

 

이 코드에서 사용된 AutoTokenizer.from_pretrained 함수는 주어진 모델 체크포인트에 대응하는 토크나이저를 로드합니다. 여기서 사용된 체크포인트 "distilbert-base-uncased-finetuned-sst-2-english"는 감정 분석 작업에 대해 미세 조정된 DistilBERT 모델입니다.

로드된 토크나이저는 입력 텍스트를 토큰으로 분할하고, 각 토큰을 모델이 이해할 수 있는 형식으로 변환하는 데 사용됩니다. 이 토크나이저를 사용하여 모델에 입력 데이터를 전처리할 수 있습니다.

 

Once we have the tokenizer, we can directly pass our sentences to it and we’ll get back a dictionary that’s ready to feed to our model! The only thing left to do is to convert the list of input IDs to tensors.

 

토크나이저가 있으면 문장을 직접 전달할 수 있고 모델에 제공할 준비가 된 사전을 다시 얻을 수 있습니다! 이제 남은 일은 입력 ID 목록을 텐서로 변환하는 것뿐입니다.

 

You can use 🤗 Transformers without having to worry about which ML framework is used as a backend; it might be PyTorch or TensorFlow, or Flax for some models. However, Transformer models only accept tensors as input. If this is your first time hearing about tensors, you can think of them as NumPy arrays instead. A NumPy array can be a scalar (0D), a vector (1D), a matrix (2D), or have more dimensions. It’s effectively a tensor; other ML frameworks’ tensors behave similarly, and are usually as simple to instantiate as NumPy arrays.

 

어떤 ML 프레임워크가 백엔드로 사용되는지 걱정할 필요 없이 🤗 Transformers를 사용할 수 있습니다. 일부 모델의 경우 PyTorch, TensorFlow 또는 Flax일 수 있습니다. 그러나 Transformer 모델은 텐서만 입력으로 허용합니다. 텐서에 대해 처음 듣는 경우 대신 NumPy 배열로 생각할 수 있습니다. NumPy 배열은 스칼라(0D), 벡터(1D), 행렬(2D)이거나 더 많은 차원을 가질 수 있습니다. 사실상 텐서입니다. 다른 ML 프레임워크의 텐서는 비슷하게 동작하며 일반적으로 NumPy 배열만큼 인스턴스화하기가 간단합니다.

 

To specify the type of tensors we want to get back (PyTorch, TensorFlow, or plain NumPy), we use the return_tensors argument:

 

반환하려는 텐서 유형(PyTorch, TensorFlow 또는 일반 NumPy)을 지정하려면 return_tensors 인수를 사용합니다.

 

raw_inputs = [
    "I've been waiting for a HuggingFace course my whole life.",
    "I hate this so much!",
]
inputs = tokenizer(raw_inputs, padding=True, truncation=True, return_tensors="pt")
print(inputs)

 

이 코드는 Hugging Face Transformers 라이브러리를 사용하여 텍스트 데이터를 전처리하는 예제입니다. 코드의 주요 부분은 tokenizer의 사용입니다.

 

  1. raw_inputs: 원시 입력 텍스트의 리스트로, 각각의 텍스트는 모델에 입력될 문장을 나타냅니다.
  2. tokenizer: AutoTokenizer.from_pretrained로 로드한 토크나이저를 사용하여 입력 데이터를 전처리합니다. 여기서는 padding, truncation, return_tensors 등의 인자를 사용하여 입력 데이터를 모델에 맞는 형식으로 변환합니다.
    • padding=True: 입력 시퀀스의 길이를 맞추기 위해 패딩을 추가합니다.
    • truncation=True: 입력 시퀀스가 모델의 최대 길이를 초과할 경우 자르기(truncate)를 수행합니다.
    • return_tensors="pt": PyTorch 텐서 형식으로 결과를 반환합니다.
  3. inputs: 전처리가 완료된 입력 데이터를 나타내는 딕셔너리입니다. 딕셔너리는 input_ids, attention_mask, 등의 필드를 포함합니다.
  4. print(inputs): 최종적으로 전처리된 입력 데이터를 출력합니다.

이 코드를 통해 텍스트 데이터를 모델이 이해할 수 있는 형식으로 변환하고, 필요에 따라 패딩 및 자르기를 수행하여 모델에 입력할 수 있습니다.

 

Don’t worry about padding and truncation just yet; we’ll explain those later. The main things to remember here are that you can pass one sentence or a list of sentences, as well as specifying the type of tensors you want to get back (if no type is passed, you will get a list of lists as a result).

 

아직은 패딩과 잘림에 대해 걱정하지 마세요. 나중에 설명하겠습니다. 여기서 기억해야 할 주요 사항은 한 문장 또는 문장 목록을 전달할 수 있을 뿐만 아니라 반환하려는 텐서 유형을 지정할 수 있다는 것입니다(유형이 전달되지 않으면 결과적으로 list of lists 을 얻게 됩니다). .

 

Here’s what the results look like as PyTorch tensors:

 

PyTorch 텐서의 결과는 다음과 같습니다.

 

{
    'input_ids': tensor([
        [  101,  1045,  1005,  2310,  2042,  3403,  2005,  1037, 17662, 12172, 2607,  2026,  2878,  2166,  1012,   102],
        [  101,  1045,  5223,  2023,  2061,  2172,   999,   102,     0,     0,     0,     0,     0,     0,     0,     0]
    ]), 
    'attention_mask': tensor([
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
    ])
}

 

 

 

The output itself is a dictionary containing two keys, input_ids and attention_mask. input_ids contains two rows of integers (one for each sentence) that are the unique identifiers of the tokens in each sentence. We’ll explain what the attention_mask is later in this chapter.

 

출력 자체는 input_ids 및 attention_mask라는 두 개의 키를 포함하는 사전입니다. input_ids에는 각 문장에 있는 토큰의 고유 식별자인 두 행의 정수(각 문장당 하나씩)가 포함되어 있습니다. attention_mask가 무엇인지는 이 장의 뒷부분에서 설명하겠습니다.

 

Going through the model

 

We can download our pretrained model the same way we did with our tokenizer. 🤗 Transformers provides an AutoModel class which also has a from_pretrained() method:

 

토크나이저에서와 동일한 방식으로 사전 훈련된 모델을 다운로드할 수 있습니다. 🤗 Transformers는 from_pretrained() 메소드도 포함하는 AutoModel 클래스를 제공합니다.

 

from transformers import AutoModel

checkpoint = "distilbert-base-uncased-finetuned-sst-2-english"
model = AutoModel.from_pretrained(checkpoint)

 

이 코드는 Hugging Face Transformers 라이브러리를 사용하여 사전 훈련된 모델을 로드하는 예제입니다.

 

여기서 사용된 AutoModel.from_pretrained 함수는 주어진 모델 체크포인트에 해당하는 사전 훈련된 모델을 로드합니다. 이 예제에서 사용된 체크포인트 "distilbert-base-uncased-finetuned-sst-2-english"는 감정 분석 작업에 대해 미세 조정된 DistilBERT 모델입니다.

로드된 모델은 해당 언어 모델의 가중치와 아키텍처를 포함하고 있습니다. 이 모델은 주어진 문제나 작업에 대해 특정한 특성을 학습했으며, 이를 활용하여 다양한 NLP 작업을 수행할 수 있습니다.

로드된 모델은 주로 추론이나 특정 작업에 활용되며, 입력 데이터에 대한 예측이나 특성 추출을 수행할 수 있습니다.

 

In this code snippet, we have downloaded the same checkpoint we used in our pipeline before (it should actually have been cached already) and instantiated a model with it.

 

이 코드 조각에서는 이전에 파이프라인에서 사용한 것과 동일한 체크포인트를 다운로드하고(실제로는 이미 캐시되었어야 함) 이를 사용하여 모델을 인스턴스화했습니다.

 

This architecture contains only the base Transformer module: given some inputs, it outputs what we’ll call hidden states, also known as features. For each model input, we’ll retrieve a high-dimensional vector representing the contextual understanding of that input by the Transformer model.

 

이 아키텍처에는 기본 Transformer 모듈만 포함되어 있습니다. 일부 입력이 주어지면 hidden states ( features 이라고도 함)를 출력합니다. 각 모델 입력에 대해 Transformer 모델의 해당 입력에 대한 맥락적 이해를 나타내는 고차원 벡터를 검색합니다.

 

If this doesn’t make sense, don’t worry about it. We’ll explain it all later.

 

이해가 되지 않더라도 걱정하지 마세요. 나중에 모두 설명하겠습니다.

 

While these hidden states can be useful on their own, they’re usually inputs to another part of the model, known as the head. In Chapter 1, the different tasks could have been performed with the same architecture, but each of these tasks will have a different head associated with it.

 

이러한 hidden states 는 그 자체로 유용할 수 있지만 일반적으로 head 라고 하는 모델의 다른 부분에 대한 입력입니다. 1장에서는 동일한 아키텍처로 다양한 작업을 수행할 수 있었지만 이러한 각 작업에는 이와 관련된 각각 다른 head 가 있습니다.

 

A high-dimensional vector?

The vector output by the Transformer module is usually large. It generally has three dimensions:

 

Transformer 모듈의 벡터 출력은 일반적으로 큽니다. 일반적으로 다음과 같은 세 가지 차원을 갖습니다.

  • Batch size: The number of sequences processed at a time (2 in our example).

  • 배치 크기: 한 번에 처리되는 시퀀스 수(예제에서는 2)입니다.

  • Sequence length: The length of the numerical representation of the sequence (16 in our example).

  • 시퀀스 길이: 시퀀스의 숫자 표현 길이입니다(이 예에서는 16).

  • Hidden size: The vector dimension of each model input.

  • 숨겨진 크기: 각 모델 입력의 벡터 차원입니다.

It is said to be “high dimensional” because of the last value. The hidden size can be very large (768 is common for smaller models, and in larger models this can reach 3072 or more).

 

마지막 값 때문에 "고차원"이라고 합니다. 숨겨진 크기는 매우 클 수 있습니다(소형 모델에서는 768이 일반적이고 대형 모델에서는 3072 이상에 도달할 수 있음).

 

We can see this if we feed the inputs we preprocessed to our model:

 

전처리한 입력을 모델에 공급하면 이를 확인할 수 있습니다.

 

outputs = model(**inputs)
print(outputs.last_hidden_state.shape)

 

torch.Size([2, 16, 768])

 

이 코드는 Hugging Face Transformers 라이브러리를 사용하여 모델에 입력 데이터를 전달하고 모델의 출력을 확인하는 예제입니다.

 

  1. outputs = model(**inputs): 모델에 입력 데이터를 전달합니다. inputs는 이전 코드에서 전처리된 텍스트 데이터를 모델이 이해할 수 있는 형식으로 변환한 결과입니다. model은 이전에 로드한 사전 훈련된 모델입니다.
  2. print(outputs.last_hidden_state.shape): 모델의 출력 중에서 last_hidden_state의 모양(shape)을 출력합니다. last_hidden_state는 모델의 마지막 숨겨진 상태를 나타내며, 이는 주어진 입력 시퀀스에 대한 모델의 표현을 담고 있습니다.

예를 들어, 출력된 모양이 (batch_size, sequence_length, hidden_size)라면, 각 차원의 의미는 다음과 같습니다:

  • batch_size: 현재 배치의 샘플 수
  • sequence_length: 입력 시퀀스의 토큰 수
  • hidden_size: 모델의 각 토큰에 대한 표현 차원의 크기

따라서 outputs.last_hidden_state.shape을 통해 모델이 입력에 대해 어떤 형태의 표현을 생성했는지 확인할 수 있습니다. 이는 모델의 내부 표현을 이해하고 다음 단계로의 전처리나 작업을 계획하는 데 도움이 됩니다.

 

 

Note that the outputs of 🤗 Transformers models behave like namedtuples or dictionaries. You can access the elements by attributes (like we did) or by key (outputs["last_hidden_state"]), or even by index if you know exactly where the thing you are looking for is (outputs[0]).

 

🤗 Transformers 모델의 출력은 명명된 튜플이나 사전처럼 동작합니다. 속성(우리가 했던 것처럼)이나 키(outputs["last_hidden_state"]) 또는 찾고 있는 항목이 어디에 있는지 정확히 아는 경우(outputs[0]) 인덱스를 통해 요소에 액세스할 수 있습니다.

 

Model heads: Making sense out of numbers

The model heads take the high-dimensional vector of hidden states as input and project them onto a different dimension. They are usually composed of one or a few linear layers:

 

model headshidden states 의 고차원 벡터를 입력으로 사용하여 이를 다른 차원에 투영합니다. 일반적으로 하나 또는 몇 개의 선형 레이어로 구성됩니다.

 

 

The output of the Transformer model is sent directly to the model head to be processed.

 

Transformer 모델의 출력은 처리를 위해 모델 헤드로 직접 전송됩니다.

 

In this diagram, the model is represented by its embeddings layer and the subsequent layers. The embeddings layer converts each input ID in the tokenized input into a vector that represents the associated token. The subsequent layers manipulate those vectors using the attention mechanism to produce the final representation of the sentences.

 

이 다이어그램에서 모델은 임베딩 레이어와 subsequent 레이어로 표현됩니다. 임베딩 레이어는 토큰화된 입력의 각 입력 ID를 연결된 토큰을 나타내는 벡터로 변환합니다. subsequent 레이어에서는 Attention 메커니즘을 사용하여 해당 벡터를 조작하여 문장의 최종 표현을 생성합니다.

 

There are many different architectures available in 🤗 Transformers, with each one designed around tackling a specific task. Here is a non-exhaustive list:

 

🤗 Transformers에는 다양한 아키텍처가 있으며, 각 아키텍처는 특정 작업을 처리하도록 설계되었습니다. 다음은 전체 목록이 아닙니다.

 

  • *Model (retrieve the hidden states)
  • *ForCausalLM
  • *ForMaskedLM
  • *ForMultipleChoice
  • *ForQuestionAnswering
  • *ForSequenceClassification
  • *ForTokenClassification
  • and others 🤗

 

For our example, we will need a model with a sequence classification head (to be able to classify the sentences as positive or negative). So, we won’t actually use the AutoModel class, but AutoModelForSequenceClassification:

 

이 예에서는 문장을 긍정 또는 부정으로 분류할 수 있도록 sequence classification head 가 있는 모델이 필요합니다. 따라서 실제로 AutoModel 클래스를 사용하지 않고 AutoModelForSequenceClassification을 사용합니다.

 

from transformers import AutoModelForSequenceClassification

checkpoint = "distilbert-base-uncased-finetuned-sst-2-english"
model = AutoModelForSequenceClassification.from_pretrained(checkpoint)
outputs = model(**inputs)

 

이 코드는 Hugging Face Transformers 라이브러리를 사용하여 사전 훈련된 시퀀스 분류 모델을 로드하고, 해당 모델에 입력 데이터를 전달하는 예제입니다.

 

  1. AutoModelForSequenceClassification.from_pretrained(checkpoint): 주어진 체크포인트에 해당하는 사전 훈련된 시퀀스 분류 모델을 로드합니다. 이 모델은 주로 텍스트 분류와 같은 작업을 위해 사전에 훈련되었습니다.
  2. outputs = model(**inputs): 로드한 모델에 전처리된 입력 데이터인 inputs를 전달하여 모델의 출력을 얻습니다. 여기서 inputs는 이전에 전처리된 텍스트 데이터에 대한 모델의 입력 형식입니다. 모델은 입력에 대해 예측값을 생성하거나 특정 작업에 필요한 표현을 출력할 것입니다.

이 코드를 통해 텍스트 분류 모델이 주어진 입력 데이터에 대해 어떻게 예측을 수행하는지를 확인할 수 있습니다. 이 모델은 주어진 문장의 클래스(긍정, 부정 등)를 예측하는 데 사용될 수 있습니다.

 

Now if we look at the shape of our outputs, the dimensionality will be much lower: the model head takes as input the high-dimensional vectors we saw before, and outputs vectors containing two values (one per label):

 

이제 출력의 모양을 살펴보면 차원이 훨씬 낮아집니다. 모델 헤드는 이전에 본 고차원 벡터를 입력으로 사용하고 두 값(레이블당 하나씩)을 포함하는 벡터를 출력합니다.

 

print(outputs.logits.shape)

 

이 코드는 Hugging Face Transformers 라이브러리를 사용하여 모델의 출력인 로짓(logits)의 모양(shape)을 출력하는 예제입니다.

 

  1. outputs.logits: 모델의 출력 중에서 예측된 클래스에 대한 로짓 값을 나타냅니다. 로짓은 주로 소프트맥스 함수를 통과하기 전의 확률에 해당합니다.
  2. outputs.logits.shape: 로짓의 모양을 출력합니다. 이는 PyTorch 텐서의 모양으로, (batch_size, num_labels)와 같은 형태일 것입니다.
    • batch_size: 현재 배치의 샘플 수
    • num_labels: 모델이 분류하려는 클래스 또는 레이블의 수

예를 들어, 출력된 모양이 (2, 2)라면, 이는 현재 배치에 두 개의 샘플이 있고 각 샘플에 대해 두 개의 클래스(레이블)에 대한 로짓 값을 가지고 있다는 것을 나타냅니다.

이 코드를 통해 모델이 입력 데이터에 대해 어떤 형태의 로짓을 출력하는지 확인할 수 있으며, 이를 통해 모델의 예측 결과를 이해할 수 있습니다.

 

torch.Size([2, 2])

 

 

 

Since we have just two sentences and two labels, the result we get from our model is of shape 2 x 2.

 

두 개의 문장과 두 개의 레이블만 있으므로 모델에서 얻은 결과는 2 x 2 모양입니다.

Postprocessing the output

The values we get as output from our model don’t necessarily make sense by themselves. Let’s take a look:

 

모델의 출력으로 얻은 값이 반드시 그 자체로 의미가 있는 것은 아닙니다. 한 번 보자:

 

print(outputs.logits)
tensor([[-1.5607,  1.6123],
        [ 4.1692, -3.3464]], grad_fn=<AddmmBackward>)

 

 

해석:

  • 첫 번째 행은 첫 번째 입력에 대한 로짓 값을 나타냅니다. 이 경우, 두 개의 클래스에 대한 로짓이 각각 -1.5607와 1.6123입니다.
  • 두 번째 행은 두 번째 입력에 대한 로짓 값을 나타냅니다. 여기서는 두 개의 클래스에 대한 로짓이 각각 4.1692와 -3.3464입니다.

로짓 값은 주로 소프트맥스 함수를 통과하여 확률 값으로 변환됩니다. 소프트맥스를 통과한 후, 각 클래스에 대한 확률이 얻어지게 됩니다. 일반적으로 확률이 가장 높은 클래스가 모델의 예측 클래스가 됩니다.

이를 통해 모델의 예측 결과를 확인하고, 어떤 클래스에 모델이 더 강한 확신을 갖고 있는지를 알 수 있습니다.

 

Our model predicted [-1.5607, 1.6123] for the first sentence and [ 4.1692, -3.3464] for the second one. Those are not probabilities but logits, the raw, unnormalized scores outputted by the last layer of the model. To be converted to probabilities, they need to go through a SoftMax layer (all 🤗 Transformers models output the logits, as the loss function for training will generally fuse the last activation function, such as SoftMax, with the actual loss function, such as cross entropy):

 

우리 모델은 첫 번째 문장에 대해 [-1.5607, 1.6123]을 예측하고 두 번째 문장에 대해 [4.1692, -3.3464]를 예측했습니다. 이는 확률이 아니라 모델의 마지막 계층에서 출력되는 정규화되지 않은 원시 점수인 로짓입니다. 확률로 변환하려면 SoftMax 레이어를 통과해야 합니다(모든 🤗 Transformers 모델은 로짓을 출력합니다. 훈련용 손실 함수는 일반적으로 교차 엔트로피와 같은 실제 손실 함수와 마지막 활성화 함수(SoftMax같은 함)를 융합하기 때문입니다).

 

import torch

predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
print(predictions)

 

tensor([[4.0195e-02, 9.5980e-01],
        [9.9946e-01, 5.4418e-04]], grad_fn=<SoftmaxBackward>)

 

이 코드는 PyTorch를 사용하여 모델의 로짓(logits) 값을 소프트맥스(softmax) 함수를 통과시켜 확률로 변환하는 작업을 수행하고, 변환된 확률 값을 출력하는 예제입니다.

 

  • torch.nn.functional.softmax(outputs.logits, dim=-1): outputs.logits 텐서에 대해 소프트맥스 함수를 적용합니다. 소프트맥스 함수는 각 원소를 [0, 1] 범위로 변환하여 전체 합이 1이 되도록 만듭니다. 이를 통해 로짓 값이 클래스에 대한 확률 값으로 변환됩니다. dim=-1은 마지막 차원(여기서는 클래스 차원)을 기준으로 소프트맥스를 계산한다는 것을 의미합니다.
  • print(predictions): 소프트맥스 함수를 통과한 결과인 변환된 확률 값을 출력합니다.

출력된 값은 확률로, 각 클래스에 대한 확률 값이 표시됩니다. 이러한 확률 값은 각 클래스에 속할 확률을 의미하며, 일반적으로 가장 높은 확률 값을 가진 클래스가 모델의 최종 예측 클래스가 됩니다.

이를 통해 모델이 예측한 클래스에 대한 확률 값을 확인할 수 있습니다.

 

 

 

Now we can see that the model predicted [0.0402, 0.9598] for the first sentence and [0.9995, 0.0005] for the second one. These are recognizable probability scores.

 

이제 모델이 첫 번째 문장에 대해 [0.0402, 0.9598]을 예측하고 두 번째 문장에 대해 [0.9995, 0.0005]를 예측한 것을 볼 수 있습니다. 이는 인식 가능한 확률 점수입니다.

 

To get the labels corresponding to each position, we can inspect the id2label attribute of the model config (more on this in the next section):

 

각 위치에 해당하는 라벨을 얻으려면 모델 구성의 id2label 속성을 검사하면 됩니다(자세한 내용은 다음 섹션에서 확인하세요).

 

model.config.id2label
{0: 'NEGATIVE', 1: 'POSITIVE'}

 

이 코드는 Hugging Face Transformers 라이브러리의 모델 설정(configuration)에서 클래스 레이블을 숫자에서 레이블 문자열로 매핑하는 딕셔너리를 반환합니다. 구체적으로는 id2label 속성을 사용하고 있습니다.

 

해석:

  • model.config: 모델의 설정(configuration)을 나타내는 객체에 접근합니다.
  • id2label: 클래스의 숫자 식별자(ID)를 해당 클래스의 레이블 문자열로 매핑하는 딕셔너리입니다.

이 딕셔너리는 주로 다중 클래스 분류 작업에서 모델이 각 클래스에 대해 할당한 숫자 ID를 해당 클래스의 레이블로 매핑하는 데 사용됩니다. 이 매핑은 모델의 출력에서 어떤 클래스가 예측되었는지를 이해하고 해석하는 데 도움이 됩니다.

예를 들어, 딕셔너리가 다음과 같다면:

 

{0: 'negative', 1: 'positive'}

 

이는 모델이 0을 부정(negative) 클래스로, 1을 긍정(positive) 클래스로 예측한다는 것을 의미합니다. 이러한 딕셔너리를 통해 모델의 예측 결과를 해석할 수 있습니다.

 

 

Now we can conclude that the model predicted the following:

 

이제 모델이 다음을 예측했다는 결론을 내릴 수 있습니다.

 

  • First sentence: NEGATIVE: 0.0402, POSITIVE: 0.9598

  • 첫 번째 문장: 부정: 0.0402, 긍정: 0.9598

  • Second sentence: NEGATIVE: 0.9995, POSITIVE: 0.0005

  • 두 번째 문장: 부정: 0.9995, 긍정: 0.0005

We have successfully reproduced the three steps of the pipeline: preprocessing with tokenizers, passing the inputs through the model, and postprocessing! Now let’s take some time to dive deeper into each of those steps.

 

우리는 파이프라인의 세 단계, 즉 토크나이저를 사용한 전처리, 모델을 통해 입력 전달, 후처리를 성공적으로 재현했습니다! 이제 각 단계에 대해 자세히 알아보는 시간을 갖도록 하겠습니다.

 

✏️ Try it out! Choose two (or more) texts of your own and run them through the sentiment-analysis pipeline. Then replicate the steps you saw here yourself and check that you obtain the same results!

 

✏️ 한번 사용해 보세요! 두 개 이상의 텍스트를 선택하고 감정 분석 파이프라인을 통해 실행하세요. 그런 다음 여기에서 본 단계를 직접 재현하고 동일한 결과를 얻는지 확인하세요!

 

Summary 

 

이 단원은 아래와 같은 코드를 실행하면 backend 단위에서 어떤 일이 일어나는지 알아볼 수 있는 메소드들을 소개 하고 있음

 

 

sentiment-analysis를 사용해서 입력 문장에 대한 긍정과 부정 여부를 출력으로 얻었는데 이 결과를 얻기 위해 내부적으로는 아래와 같은 단계를 가짐.

 

1. 입력값들을 기계가 알 수 있도록 토큰화 한다. AutoTokenizer를 사용하면 입력값에 대한 토큰 값을 얻을 수 있음

2. 토큰 값을 사전 훈련된 모델에 통과 시켜 hidden_state 값을 얻는다. AutoModel을 사용하면 해당 hidden_state 값에 대한 정보를 알 수 있음
긍정 부정을 구별하려면 AutoModel 대신 AutoModelForSequenceClassification 모델을 사용해서 logit 값을 얻을 수 있음

이 에제 에서는 AutoModel 대신 AutoModelForSequenceClassification 모델을 사용했음

3. logit 값을 softmax에 통과 시켜 확률 값으로 변환한다. torch.nn.functional.softmax() 함수를 사용함

 

이러한 과정을 거쳐 위와 같은 결과를 얻게 된 것임.

 

 

반응형


반응형

https://huggingface.co/learn/nlp-course/chapter2/1?fw=pt

 

Introduction - Hugging Face NLP Course

2. Using 🤗 Transformers 3. Fine-tuning a pretrained model 4. Sharing models and tokenizers 5. The 🤗 Datasets library 6. The 🤗 Tokenizers library 9. Building and sharing demos new

huggingface.co

 

 

As you saw in Chapter 1, Transformer models are usually very large. With millions to tens of billions of parameters, training and deploying these models is a complicated undertaking. Furthermore, with new models being released on a near-daily basis and each having its own implementation, trying them all out is no easy task.

 

1장에서 본 것처럼 Transformer 모델은 일반적으로 매우 큽니다. 수백만에서 수백억 개의 매개변수를 사용하여 이러한 모델을 교육하고 배포하는 것은 복잡한 작업입니다. 더욱이 새로운 모델이 거의 매일 출시되고 각각 자체 구현이 있기 때문에 모든 모델을 시험해 보는 것은 쉬운 일이 아닙니다.

 

The 🤗 Transformers library was created to solve this problem. Its goal is to provide a single API through which any Transformer model can be loaded, trained, and saved. The library’s main features are:

 

🤗 Transformers 라이브러리는 이 문제를 해결하기 위해 만들어졌습니다. 목표는 모든 Transformer 모델을 로드하고, 훈련하고, 저장할 수 있는 단일 API를 제공하는 것입니다. library 의 주요 기능은 다음과 같습니다.

 

  • Ease of use: Downloading, loading, and using a state-of-the-art NLP model for inference can be done in just two lines of code.

  • 사용 용이성: 단 두 줄의 코드로 추론을 위한 최첨단 NLP 모델을 다운로드, 로드 및 사용할 수 있습니다.

  • Flexibility: At their core, all models are simple PyTorch nn.Module or TensorFlow tf.keras.Model classes and can be handled like any other models in their respective machine learning (ML) frameworks.

  • 유연성: 기본적으로 모든 모델은 간단한 PyTorch nn.Module 또는 TensorFlow tf.keras.Model 클래스이며 해당 기계 학습(ML) 프레임워크에서 다른 모델처럼 처리될 수 있습니다.
  • Simplicity: Hardly any abstractions are made across the library. The “All in one file” is a core concept: a model’s forward pass is entirely defined in a single file, so that the code itself is understandable and hackable.

  • 단순성: 라이브러리 전반에 걸쳐 추상화가 거의 이루어지지 않습니다. "All in one file"이 핵심 개념입니다. 모델의 정방향 전달이 단일 파일에 완전히 정의되므로 코드 자체를 이해하고 해킹할 수 있습니다.

This last feature makes 🤗 Transformers quite different from other ML libraries. The models are not built on modules that are shared across files; instead, each model has its own layers. In addition to making the models more approachable and understandable, this allows you to easily experiment on one model without affecting others.

 

이 마지막 기능은 🤗 Transformer를 다른 ML 라이브러리와 상당히 다르게 만듭니다. 모델은 파일 간에 공유되는 모듈을 기반으로 구축되지 않습니다. 대신 각 모델에는 자체 레이어가 있습니다. 모델을 더욱 접근하기 쉽고 이해하기 쉽게 만드는 것 외에도 다른 모델에 영향을 주지 않고 한 모델을 쉽게 실험할 수 있습니다.

 

This chapter will begin with an end-to-end example where we use a model and a tokenizer together to replicate the pipeline() function introduced in Chapter 1. Next, we’ll discuss the model API: we’ll dive into the model and configuration classes, and show you how to load a model and how it processes numerical inputs to output predictions.

 

이 장은 모델과 토크나이저를 함께 사용하여 1장에서 소개한 파이프라인() 함수를 복제하는 엔드투엔드 예제로 시작합니다. 다음으로 모델 API에 대해 논의하겠습니다. 모델 및 구성 클래스를 자세히 살펴보고 모델을 로드하는 방법과 숫자 입력을 처리하여 예측을 출력하는 방법을 보여 드리겠습니다.

 

Then we’ll look at the tokenizer API, which is the other main component of the pipeline() function. Tokenizers take care of the first and last processing steps, handling the conversion from text to numerical inputs for the neural network, and the conversion back to text when it is needed. Finally, we’ll show you how to handle sending multiple sentences through a model in a prepared batch, then wrap it all up with a closer look at the high-level tokenizer() function.

 

그런 다음 파이프라인() 함수의 또 다른 주요 구성 요소인 토크나이저 API를 살펴보겠습니다. 토크나이저는 첫 번째와 마지막 처리 단계를 처리하여 텍스트를 신경망의 숫자 입력으로 변환하고 필요할 때 다시 텍스트로 변환하는 작업을 처리합니다. 마지막으로, 준비된 배치에서 모델을 통해 여러 문장 전송을 처리하는 방법을 보여주고, 상위 수준 tokenizer() 함수를 자세히 살펴보며 마무리하겠습니다.

 

⚠️ In order to benefit from all features available with the Model Hub and 🤗 Transformers, we recommend creating an account.

 

⚠️ Model Hub 및 🤗 Transformers에서 사용할 수 있는 모든 기능을 활용하려면 계정을 만드는 것이 좋습니다.

 

 

 

 

 

 

 

반응형


반응형

https://huggingface.co/learn/nlp-course/chapter1/10?fw=pt

 

End-of-chapter quiz - Hugging Face NLP Course

2. Using 🤗 Transformers 3. Fine-tuning a pretrained model 4. Sharing models and tokenizers 5. The 🤗 Datasets library 6. The 🤗 Tokenizers library 9. Building and sharing demos new

huggingface.co

 

This chapter covered a lot of ground! Don’t worry if you didn’t grasp all the details; the next chapters will help you understand how things work under the hood.

 

이 장에서는 많은 내용을 다루었습니다! 모든 세부 사항을 파악하지 못했다고 걱정하지 마세요. 다음 장에서는 내부적으로 작동하는 방식을 이해하는 데 도움이 될 것입니다.

 

First, though, let’s test what you learned in this chapter!

 

하지만 먼저 이 장에서 배운 내용을 테스트해 보겠습니다.

 

 

https://huggingface.co/roberta-large-mnli

 

roberta-large-mnli · Hugging Face

🌍 amsterdamNLP/attention-rollout 📚 Snowball/Watermarking_Generate_Text 🏃 binqiangliu/HuggingFaceH4-StarChat-Beta-Pipeline 🚀 luiscgp/Fact_Checking_Blue_Amazon 📚 yizhangliu/Grounded-Segment-Anything 🐠 rrevoid/article_classifier 📚 slachit

huggingface.co

 

 

 

 

 

 

 

 

 

 

 

 

 

 

반응형

HF-NLP-Transformer models : Summary

2023. 12. 24. 05:56 | Posted by 솔웅


반응형

https://huggingface.co/learn/nlp-course/chapter1/9?fw=pt

 

Summary - Hugging Face NLP Course

2. Using 🤗 Transformers 3. Fine-tuning a pretrained model 4. Sharing models and tokenizers 5. The 🤗 Datasets library 6. The 🤗 Tokenizers library 9. Building and sharing demos new

huggingface.co

 

In this chapter, you saw how to approach different NLP tasks using the high-level pipeline() function from 🤗 Transformers. You also saw how to search for and use models in the Hub, as well as how to use the Inference API to test the models directly in your browser.

 

이 장에서는 🤗 Transformers의 고급 파이프라인() 함수를 사용하여 다양한 NLP 작업에 접근하는 방법을 살펴보았습니다. 또한 허브에서 모델을 검색하고 사용하는 방법과 추론 API를 사용하여 브라우저에서 직접 모델을 테스트하는 방법도 살펴보았습니다.

 

We discussed how Transformer models work at a high level, and talked about the importance of transfer learning and fine-tuning. A key aspect is that you can use the full architecture or only the encoder or decoder, depending on what kind of task you aim to solve. The following table summarizes this:

 

Transformer 모델이 높은 수준에서 작동하는 방식에 대해 논의하고 전이 학습 및 미세 조정의 중요성에 대해 이야기했습니다. 중요한 측면은 해결하려는 작업 종류에 따라 전체 아키텍처를 사용하거나 인코더나 디코더만 사용할 수 있다는 것입니다. 다음 표에 이 내용이 요약되어 있습니다.

 

 

 

 

 

 

 

반응형


반응형

https://huggingface.co/learn/nlp-course/chapter1/8?fw=pt

 

Bias and limitations - Hugging Face NLP Course

2. Using 🤗 Transformers 3. Fine-tuning a pretrained model 4. Sharing models and tokenizers 5. The 🤗 Datasets library 6. The 🤗 Tokenizers library 9. Building and sharing demos new

huggingface.co

 

Bias and limitations

 

If your intent is to use a pretrained model or a fine-tuned version in production, please be aware that, while these models are powerful tools, they come with limitations. The biggest of these is that, to enable pretraining on large amounts of data, researchers often scrape all the content they can find, taking the best as well as the worst of what is available on the internet.

 

프로덕션에서 사전 학습된 모델이나 미세 조정된 버전을 사용하려는 경우 이러한 모델은 강력한 도구이기는 하지만 제한 사항이 있다는 점에 유의하세요. 그 중 가장 큰 점은 많은 양의 데이터에 대한 사전 훈련을 활성화하기 위해 연구자들이 찾을 수 있는 모든 콘텐츠를 긁어내어 인터넷에서 사용할 수 있는 콘텐츠 중 최고와 최악의 콘텐츠를 취하는 경우가 많다는 것입니다.

 

To give a quick illustration, let’s go back the example of a fill-mask pipeline with the BERT model:

 

빠른 설명을 위해 BERT 모델을 사용한 채우기 마스크 파이프라인의 예로 돌아가 보겠습니다.

 

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']

 

이 코드는 Hugging Face Transformers 라이브러리를 사용하여 BERT 모델을 활용하여 주어진 문장의 [MASK] 위치에 대한 예측을 수행하는 예제입니다.

 

from transformers import pipeline

# 'fill-mask' 파이프라인을 생성하고, 모델을 'bert-base-uncased'로 설정합니다.
unmasker = pipeline("fill-mask", model="bert-base-uncased")

# 첫 번째 문장에서 [MASK] 위치에 대한 예측을 수행하고 결과를 출력합니다.
result = unmasker("This man works as a [MASK].")
print([r["token_str"] for r in result])

# 두 번째 문장에서 [MASK] 위치에 대한 예측을 수행하고 결과를 출력합니다.
result = unmasker("This woman works as a [MASK].")
print([r["token_str"] for r in result])

 

여기에서 사용된 fill-mask 파이프라인은 주어진 문장에서 [MASK] 토큰의 위치에 대한 예측을 수행합니다. BERT 모델은 문맥을 고려하여 [MASK] 위치에 들어갈 수 있는 가장 적절한 토큰을 예측하게 됩니다.

 

출력된 결과는 각각의 [MASK] 위치에 대한 예측 결과를 나타냅니다. 출력은 확률이 높은 순으로 정렬되어 있으며, token_str 키를 통해 해당 토큰의 문자열 값을 확인할 수 있습니다.

 

이 코드는 BERT 모델을 활용하여 문장 내의 [MASK] 위치에 대한 토큰 예측을 수행하는 간단한 예제를 제시하고 있습니다.

 

 

When asked to fill in the missing word in these two sentences, the model gives only one gender-free answer (waiter/waitress). The others are work occupations usually associated with one specific gender — and yes, prostitute ended up in the top 5 possibilities the model associates with “woman” and “work.” This happens even though BERT is one of the rare Transformer models not built by scraping data from all over the internet, but rather using apparently neutral data (it’s trained on the English Wikipedia and BookCorpus datasets).

 

이 두 문장에서 누락된 단어를 채워 달라는 요청을 받으면 모델은 성별에 관계없이 단 하나의 답변(웨이터/웨이트리스)만 제공합니다. 다른 것들은 일반적으로 하나의 특정 성별과 관련된 직업입니다. 그렇습니다. 매춘부는 모델이 "여성" 및 "일"과 연관시키는 상위 5가지 가능성에 포함되었습니다. 이는 BERT가 인터넷 전체에서 데이터를 스크랩하여 구축된 것이 아니라 명백히 중립적인 데이터(English Wikipedia 및 BookCorpus 데이터세트에서 훈련됨)를 사용하여 구축된 보기 드문 Transformer 모델 중 하나임에도 불구하고 발생합니다.

 

When you use these tools, you therefore need to keep in the back of your mind that the original model you are using could very easily generate sexist, racist, or homophobic content. Fine-tuning the model on your data won’t make this intrinsic bias disappear.

 

따라서 이러한 도구를 사용할 때는 사용 중인 원래 모델이 성차별, 인종 차별, 동성애 혐오 콘텐츠를 매우 쉽게 생성할 수 있다는 점을 염두에 두어야 합니다. 데이터에 대한 모델을 미세 조정해도 이러한 본질적인 편향이 사라지지는 않습니다.

 

 

 

 

 

반응형


반응형

https://huggingface.co/learn/nlp-course/chapter1/7?fw=pt

 

Sequence-to-sequence models[sequence-to-sequence-models] - Hugging Face NLP Course

2. Using 🤗 Transformers 3. Fine-tuning a pretrained model 4. Sharing models and tokenizers 5. The 🤗 Datasets library 6. The 🤗 Tokenizers library 9. Building and sharing demos new

huggingface.co

 

https://youtu.be/0_4KEb08xrE?si=M4YD8V6SuOaJvXlP

 

 

Encoder-decoder models (also called sequence-to-sequence models) use both parts of the Transformer architecture. At each stage, the attention layers of the encoder can access all the words in the initial sentence, whereas the attention layers of the decoder can only access the words positioned before a given word in the input.

 

인코더-디코더 모델(시퀀스-시퀀스 모델이라고도 함)은 Transformer 아키텍처의 두 부분을 모두 사용합니다. 각 단계에서 인코더의 어텐션 레이어는 초기 문장의 모든 단어에 액세스할 수 있는 반면, 디코더의 어텐션 레이어는 입력에서 특정 단어 앞에 위치한 단어에만 액세스할 수 있습니다.

 

The pretraining of these models can be done using the objectives of encoder or decoder models, but usually involves something a bit more complex. For instance, T5 is pretrained by replacing random spans of text (that can contain several words) with a single mask special word, and the objective is then to predict the text that this mask word replaces.

 

이러한 모델의 사전 훈련은 인코더 또는 디코더 모델의 목적을 사용하여 수행될 수 있지만 일반적으로 좀 더 복잡한 작업이 포함됩니다. 예를 들어, T5는 임의의 텍스트 범위(여러 단어를 포함할 수 있음)를 단일 마스크 특수 단어로 대체하여 사전 학습되었으며, 그런 다음 목표는 이 마스크 단어가 대체할 텍스트를 예측하는 것입니다.

 

Sequence-to-sequence models are best suited for tasks revolving around generating new sentences depending on a given input, such as summarization, translation, or generative question answering.

 

Sequence-to-Sequence 모델은 요약, 번역 또는 생성적 질문 답변과 같이 주어진 입력에 따라 새로운 문장을 생성하는 작업에 가장 적합합니다.

 

Representatives of this family of models include:

 

이 모델 제품군의 대표자는 다음과 같습니다.

 

 

 

 

반응형


반응형

https://huggingface.co/learn/nlp-course/chapter1/6?fw=pt

 

Decoder models - Hugging Face NLP Course

2. Using 🤗 Transformers 3. Fine-tuning a pretrained model 4. Sharing models and tokenizers 5. The 🤗 Datasets library 6. The 🤗 Tokenizers library 9. Building and sharing demos new

huggingface.co

 

https://youtu.be/d_ixlCubqQw?si=K9zIkyOcYjir30si

 

Decoder models use only the decoder of a Transformer model. At each stage, for a given word the attention layers can only access the words positioned before it in the sentence. These models are often called auto-regressive models.

 

디코더 모델은 Transformer 모델의 디코더만 사용합니다. 각 단계에서 주어진 단어에 대해 어텐션 레이어는 문장에서 그 단어 앞에 위치한 단어에만 접근할 수 있습니다. 이러한 모델을 종종 자동 회귀 모델이라고 합니다.

 

The pretraining of decoder models usually revolves around predicting the next word in the sentence.

 

디코더 모델의 사전 학습은 일반적으로 문장의 다음 단어를 예측하는 것입니다.

 

These models are best suited for tasks involving text generation.

 

이러한 모델은 텍스트 생성과 관련된 작업에 가장 적합합니다.

 

Representatives of this family of models include:

 

이 모델 제품군의 대표자는 다음과 같습니다.

 

 

 

 

 

 

 

 

 

 

 

반응형


반응형

https://huggingface.co/learn/nlp-course/chapter1/5?fw=pt

 

Encoder models - Hugging Face NLP Course

2. Using 🤗 Transformers 3. Fine-tuning a pretrained model 4. Sharing models and tokenizers 5. The 🤗 Datasets library 6. The 🤗 Tokenizers library 9. Building and sharing demos new

huggingface.co

 

 

https://youtu.be/MUqNwgPjJvQ?si=0uK-B2FJcPmGBNcy

 

 

Encoder models use only the encoder of a Transformer model. At each stage, the attention layers can access all the words in the initial sentence. These models are often characterized as having “bi-directional” attention, and are often called auto-encoding models.

 

인코더 모델은 Transformer 모델의 인코더만 사용합니다. 각 단계에서 Attention 레이어는 초기 문장의 모든 단어에 접근할 수 있습니다. 이러한 모델은 종종 "양방향" 주의를 기울이는 특징이 있으며 자동 인코딩 모델이라고도 합니다.

 

The pretraining of these models usually revolves around somehow corrupting a given sentence (for instance, by masking random words in it) and tasking the model with finding or reconstructing the initial sentence.

 

이러한 모델의 사전 학습은 일반적으로 주어진 문장을 어떻게든 손상시키고(예: 임의의 단어를 마스킹하여) 초기 문장을 찾거나 재구성하는 작업을 모델에 맡기는 것을 중심으로 진행됩니다.

 

Encoder models are best suited for tasks requiring an understanding of the full sentence, such as sentence classification, named entity recognition (and more generally word classification), and extractive question answering.

 

인코더 모델은 문장 분류, 명명된 엔터티 인식(더 일반적으로는 단어 분류), 추출적 질문 응답 등 전체 문장에 대한 이해가 필요한 작업에 가장 적합합니다.

 

Representatives of this family of models include:

 

이 모델 제품군의 대표자는 다음과 같습니다.

 

 

 

 

 

반응형


반응형

https://huggingface.co/learn/nlp-course/chapter1/4?fw=pt

 

How do Transformers work? - Hugging Face NLP Course

2. Using 🤗 Transformers 3. Fine-tuning a pretrained model 4. Sharing models and tokenizers 5. The 🤗 Datasets library 6. The 🤗 Tokenizers library 9. Building and sharing demos new

huggingface.co

 

How do Transformers work?

 

In this section, we will take a high-level look at the architecture of Transformer models.

 

이 섹션에서는 Transformer 모델의 아키텍처를 high-level look 해 보겠습니다.

 

A bit of Transformer history

Here are some reference points in the (short) history of Transformer models:

 

다음은 Transformer 모델의 (짧은) 역사에 대한 몇 가지 참고 사항입니다.

 

 

The Transformer architecture was introduced in June 2017. The focus of the original research was on translation tasks. This was followed by the introduction of several influential models, including:

 

Transformer 아키텍처는 2017년 6월에 도입되었습니다. 원래 연구의 초점은 번역 작업이었습니다. 그 후 다음을 포함한 여러 영향력 있는 모델이 도입되었습니다.

 

  • June 2018: GPT, the first pretrained Transformer model, used for fine-tuning on various NLP tasks and obtained state-of-the-art results

  • 2018년 6월: 최초의 사전 훈련된 Transformer 모델인 GPT는 다양한 NLP 작업의 미세 조정에 사용되어 최첨단 결과를 얻었습니다.

  • October 2018: BERT, another large pretrained model, this one designed to produce better summaries of sentences (more on this in the next chapter!)

  • 2018년 10월: 또 다른 대형 사전 학습 모델인 BERT는 더 나은 문장 요약을 생성하도록 설계되었습니다(자세한 내용은 다음 장에서!).

  • February 2019: GPT-2, an improved (and bigger) version of GPT that was not immediately publicly released due to ethical concerns

  • 2019년 2월: 윤리적 문제로 인해 즉시 공개되지 않은 개선된(및 더 큰) 버전의 GPT인 GPT-2

  • October 2019: DistilBERT, a distilled version of BERT that is 60% faster, 40% lighter in memory, and still retains 97% of BERT’s performance

  • 2019년 10월: 60% 더 빠르고 메모리는 40% 가벼우면서도 여전히 BERT 성능의 97%를 유지하는 BERT의 증류 버전인 DitilBERT

  • October 2019: BART and T5, two large pretrained models using the same architecture as the original Transformer model (the first to do so)

  • 2019년 10월: BART 및 T5, 원래 Transformer 모델과 동일한 아키텍처를 사용하는 두 개의 사전 훈련된 모델(최초)

  • May 2020, GPT-3, an even bigger version of GPT-2 that is able to perform well on a variety of tasks without the need for fine-tuning (called zero-shot learning)

  • 2020년 5월, 미세 조정 없이 다양한 작업을 잘 수행할 수 있는 GPT-2의 더 큰 버전인 GPT-3(제로샷 학습이라고 함)

This list is far from comprehensive, and is just meant to highlight a few of the different kinds of Transformer models. Broadly, they can be grouped into three categories:

 

이 목록은 포괄적이지 않으며 단지 다양한 종류의 Transformer 모델 중 몇 가지를 강조하기 위한 것입니다. 크게는 세 가지 범주로 분류할 수 있습니다.

  • GPT-like (also called auto-regressive Transformer models)
  • BERT-like (also called auto-encoding Transformer models)
  • BART/T5-like (also called sequence-to-sequence Transformer models)

We will dive into these families in more depth later on.

 

나중에 이러한 계열에 대해 더 자세히 살펴보겠습니다.

 

 

Transformers are language models

 

All the Transformer models mentioned above (GPT, BERT, BART, T5, etc.) have been trained as language models. This means they have been trained on large amounts of raw text in a self-supervised fashion. Self-supervised learning is a type of training in which the objective is automatically computed from the inputs of the model. That means that humans are not needed to label the data!

 

위에서 언급한 모든 Transformer 모델(GPT, BERT, BART, T5 등)은 언어 모델로 학습되었습니다. 이는 그들이 자기 감독 방식으로 대량의 원시 텍스트에 대해 훈련을 받았다는 것을 의미합니다. 자기 지도 학습은 모델의 입력으로부터 목표가 자동으로 계산되는 훈련 유형입니다. 이는 데이터에 라벨을 붙이는 데 사람이 필요하지 않다는 것을 의미합니다!

 

This type of model develops a statistical understanding of the language it has been trained on, but it’s not very useful for specific practical tasks. Because of this, the general pretrained model then goes through a process called transfer learning. During this process, the model is fine-tuned in a supervised way — that is, using human-annotated labels — on a given task.

 

이러한 유형의 모델은 훈련된 언어에 대한 통계적 이해를 발전시키지만 특정 실제 작업에는 그다지 유용하지 않습니다. 이로 인해 일반 사전 학습 모델은 전이 학습이라는 과정을 거칩니다. 이 프로세스 동안 모델은 주어진 작업에 대해 지도 방식, 즉 사람이 주석을 추가한 레이블을 사용하여 미세 조정됩니다.

 

An example of a task is predicting the next word in a sentence having read the n previous words. This is called causal language modeling because the output depends on the past and present inputs, but not the future ones.

 

작업의 예는 n개의 이전 단어를 읽고 문장의 다음 단어를 예측하는 것입니다. 출력이 과거 및 현재 입력에 따라 달라지지만 미래 입력에는 영향을 받지 않기 때문에 이를 인과 언어 모델링이라고 합니다.

 

 

 

Another example is masked language modeling, in which the model predicts a masked word in the sentence.

 

또 다른 예는 모델이 문장에서 마스크된 단어를 예측하는 마스크된 언어 모델링입니다.

 

 

 

Transformers are big models

 

Apart from a few outliers (like DistilBERT), the general strategy to achieve better performance is by increasing the models’ sizes as well as the amount of data they are pretrained on.

 

DistilBERT와 같은 몇 가지 이상값을 제외하고 더 나은 성능을 달성하기 위한 일반적인 전략은 모델의 크기와 사전 학습된 데이터의 양을 늘리는 것입니다.

 

 

 

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. It even translates to environmental impact, as can be seen in the following graph.

 

불행하게도 모델, 특히 대규모 모델을 훈련하려면 많은 양의 데이터가 필요합니다. 이는 시간과 컴퓨팅 리소스 측면에서 매우 비용이 많이 듭니다. 다음 그래프에서 볼 수 있듯이 이는 환경에 미치는 영향까지 해석됩니다.

 

 

https://youtu.be/ftWlj4FBHTg?si=WsaLjWZkkn_UNqcO

 

And this is showing a project for a (very big) model led by a team consciously trying to reduce the environmental impact of pretraining. The footprint of running lots of trials to get the best hyperparameters would be even higher.

 

그리고 이것은 사전 훈련이 환경에 미치는 영향을 의식적으로 줄이기 위해 노력하는 팀이 이끄는 (매우 큰) 모델에 대한 프로젝트를 보여줍니다. 최상의 초매개변수를 얻기 위해 수많은 시도를 실행하는 데 드는 공간은 훨씬 더 커질 것입니다.

 

Imagine if each time a research team, a student organization, or a company wanted to train a model, it did so from scratch. This would lead to huge, unnecessary global costs!

 

연구팀, 학생 단체 또는 회사가 모델을 훈련하려고 할 때마다 처음부터 그렇게 했다고 상상해 보십시오. 이로 인해 막대하고 불필요한 글로벌 비용이 발생하게 됩니다!

 

This is why sharing language models is paramount: sharing the trained weights and building on top of already trained weights reduces the overall compute cost and carbon footprint of the community.

 

이것이 바로 언어 모델 공유가 중요한 이유입니다. 훈련된 가중치를 공유하고 이미 훈련된 가중치 위에 구축하면 커뮤니티의 전체 컴퓨팅 비용과 탄소 배출량이 줄어듭니다.

 

By the way, you can evaluate the carbon footprint of your models’ training through several tools. For example ML CO2 Impact or Code Carbon which is integrated in 🤗 Transformers. To learn more about this, you can read this blog post which will show you how to generate an emissions.csv file with an estimate of the footprint of your training, as well as the documentation of 🤗 Transformers addressing this topic.

 

그런데 여러 도구를 통해 모델 학습의 탄소 배출량을 평가할 수 있습니다. 예를 들어 🤗 Transformers에 통합된 ML CO2 Impact 또는 Code Carbon이 있습니다. 이에 대해 자세히 알아보려면 이 주제를 다루는 🤗 Transformers 문서뿐만 아니라 훈련 공간의 추정치를 포함하여 Emission.csv 파일을 생성하는 방법을 보여주는 이 블로그 게시물을 읽어보세요.

 

 

Transfer Learning

 

https://youtu.be/BqqfQnyjmgg?si=0PU8ouwdHZNxvzh0

 

retraining is the act of training a model from scratch: the weights are randomly initialized, and the training starts without any prior knowledge.

 

사전 훈련은 모델을 처음부터 훈련하는 행위입니다. 가중치는 무작위로 초기화되고 사전 지식 없이 훈련이 시작됩니다.

 

 

This pretraining is usually done on very large amounts of data. Therefore, it requires a very large corpus of data, and training can take up to several weeks.

 

이 사전 훈련은 일반적으로 매우 많은 양의 데이터에 대해 수행됩니다. 따라서 매우 많은 양의 데이터가 필요하며 훈련에는 최대 몇 주가 걸릴 수 있습니다.

 

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. Wait — why not simply train directly for the final task? There are a couple of reasons:

 

반면, 미세 조정은 모델이 사전 훈련된 후에 수행되는 훈련입니다. 미세 조정을 수행하려면 먼저 사전 훈련된 언어 모델을 획득한 다음 작업과 관련된 데이터 세트를 사용하여 추가 훈련을 수행합니다. 잠깐만요. 최종 작업을 위해 직접 훈련하면 어떨까요? 몇 가지 이유가 있습니다:

 

  • The pretrained model was already trained on a dataset that has some similarities with the fine-tuning dataset. The fine-tuning process is thus able to take advantage of knowledge acquired by the initial model during pretraining (for instance, with NLP problems, the pretrained model will have some kind of statistical understanding of the language you are using for your task).

  • 사전 훈련된 모델은 미세 조정 데이터 세트와 일부 유사한 데이터 세트에 대해 이미 훈련되었습니다. 따라서 미세 조정 프로세스는 사전 훈련 중에 초기 모델에서 얻은 지식을 활용할 수 있습니다(예를 들어 NLP 문제의 경우 사전 훈련된 모델은 작업에 사용하는 언어에 대해 일종의 통계적 이해를 갖습니다).

  • Since the pretrained model was already trained on lots of data, the fine-tuning requires way less data to get decent results.

  • 사전 훈련된 모델은 이미 많은 데이터에 대해 훈련되었으므로 미세 조정에 적절한 결과를 얻으려면 훨씬 적은 양의 데이터가 필요합니다.
  • For the same reason, the amount of time and resources needed to get good results are much lower.

  • 같은 이유로 좋은 결과를 얻는 데 필요한 시간과 자원의 양은 훨씬 적습니다.

For example, one could leverage a pretrained model trained on the English language and then fine-tune it on an arXiv corpus, resulting in a science/research-based model. The fine-tuning will only require a limited amount of data: the knowledge the pretrained model has acquired is “transferred,” hence the term transfer learning.

 

예를 들어, 영어로 훈련된 사전 훈련된 모델을 활용한 다음 arXiv 코퍼스에서 이를 미세 조정하여 과학/연구 기반 모델을 만들 수 있습니다. 미세 조정에는 제한된 양의 데이터만 필요합니다. 사전 훈련된 모델이 획득한 지식은 "전송"되므로 전이 학습이라는 용어가 사용됩니다.

 

 

 

Fine-tuning a model therefore has lower time, data, financial, and environmental costs. It is also quicker and easier to iterate over different fine-tuning schemes, as the training is less constraining than a full pretraining.

 

따라서 모델을 미세 조정하면 시간, 데이터, 재정, 환경 비용이 절감됩니다. 또한 훈련이 전체 사전 훈련보다 덜 제한적이므로 다양한 미세 조정 방식을 반복하는 것이 더 빠르고 쉽습니다.

 

This process will also achieve better results than training from scratch (unless you have lots of data), which is why you should always try to leverage a pretrained model — one as close as possible to the task you have at hand — and fine-tune it.

 

또한 이 프로세스는 처음부터 훈련하는 것보다 더 나은 결과를 얻을 수 있으므로(데이터가 많지 않은 경우) 항상 사전 훈련된 모델을 활용하려고 노력해야 합니다.— 현재 진행 중인 작업에 최대한 가깝게 설정하고 미세 조정하세요.

 

General architecture

 

In this section, we’ll go over the general architecture of the Transformer model. Don’t worry if you don’t understand some of the concepts; there are detailed sections later covering each of the components.

 

이 섹션에서는 Transformer 모델의 일반적인 아키텍처를 살펴보겠습니다. 일부 개념을 이해하지 못하더라도 걱정하지 마세요. 나중에 각 구성 요소를 다루는 자세한 섹션이 있습니다.

 

https://youtu.be/H39Z_720T5s?si=NTFJwNVw7AuGgE6D

 

 

Introduction

The model is primarily composed of two blocks:

 

이 모델은 기본적으로 두 개의 블록으로 구성됩니다.

 

  • Encoder (left): The encoder receives an input and builds a representation of it (its features). This means that the model is optimized to acquire understanding from the input.

  • 인코더(왼쪽): 인코더는 입력을 수신하고 이에 대한 representation  (해당 features )을 작성합니다. 이는 모델이 입력으로부터 이해를 얻도록 최적화되었음을 의미합니다.

  • Decoder (right): The decoder uses the encoder’s representation (features) along with other inputs to generate a target sequence. This means that the model is optimized for generating outputs.

  • 디코더(오른쪽): 디코더는 다른 입력과 함께 인코더의 representation  ( features )을 사용하여 대상 시퀀스를 생성합니다. 이는 모델이 출력 생성에 최적화되어 있음을 의미합니다.

 

 

Each of these parts can be used independently, depending on the task:

 

이러한 각 부분은 작업에 따라 독립적으로 사용될 수 있습니다.

 

  • Encoder-only models: Good for tasks that require understanding of the input, such as sentence classification and named entity recognition.

  • 인코더 전용 모델: 문장 분류 및 명명된 엔터티 인식과 같이 입력에 대한 이해가 필요한 작업에 적합합니다.

  • Decoder-only models: Good for generative tasks such as text generation.

  • 디코더 전용 모델: 텍스트 생성과 같은 생성 작업에 적합합니다.

  • Encoder-decoder models or sequence-to-sequence models: Good for generative tasks that require an input, such as translation or summarization.
  • 인코더-디코더 모델 또는 시퀀스-시퀀스 모델: 번역 또는 요약과 같이 입력이 필요한 생성 작업에 적합합니다.

We will dive into those architectures independently in later sections.

 

이후 섹션에서 이러한 아키텍처에 대해 독립적으로 살펴보겠습니다.

 

Attention layers

A key feature of Transformer models is that they are built with special layers called attention layers. In fact, the title of the paper introducing the Transformer architecture was “Attention Is All You Need”! We will explore the details of attention layers later in the course; for now, all you need to know is that this layer will tell the model to pay specific attention to certain words in the sentence you passed it (and more or less ignore the others) when dealing with the representation of each word.

 

Transformer 모델의 주요 특징은 Attention 레이어라는 특수 레이어로 구축된다는 것입니다. 실제로 Transformer 아키텍처를 소개하는 논문의 제목은 "Attention Is All You Need"였습니다! 이 과정의 뒷부분에서 Attention 레이어에 대한 세부 사항을 살펴보겠습니다. 지금으로서 알아야 할 것은 이 레이어가 각 단어의 표현을 처리할 때 전달한 문장의 특정 단어에 특별한 주의를 기울이고 다른 단어는 거의 무시하도록 모델에 지시한다는 것입니다.

 

To put this into context, consider the task of translating text from English to French. Given the input “You like this course”, a translation model will need to also attend to the adjacent word “You” to get the proper translation for the word “like”, because in French the verb “like” is conjugated differently depending on the subject. The rest of the sentence, however, is not useful for the translation of that word. In the same vein, when translating “this” the model will also need to pay attention to the word “course”, because “this” translates differently depending on whether the associated noun is masculine or feminine. Again, the other words in the sentence will not matter for the translation of “this”. With more complex sentences (and more complex grammar rules), the model would need to pay special attention to words that might appear farther away in the sentence to properly translate each word.

 

이를 맥락에 맞게 이해하려면 텍스트를 영어에서 프랑스어로 번역하는 작업을 고려해 보세요. "You like thiscourse"라는 입력이 주어지면 번역 모델은 "like"라는 단어에 대한 적절한 번역을 얻기 위해 인접한 단어 "You"에도 주의를 기울여야 합니다. 왜냐하면 프랑스어에서는 동사 "like"가 주제에 따라 다르게 활용되기 때문입니다. 그러나 문장의 나머지 부분은 해당 단어를 번역하는 데 유용하지 않습니다. 같은 맥락에서, "this"를 번역할 때 모델은 "course"라는 단어에도 주의를 기울여야 합니다. "this"는 관련 명사가 남성인지 여성인지에 따라 다르게 번역되기 때문입니다. 다시 말하지만, 문장의 다른 단어는 "this"를 번역하는 데 중요하지 않습니다. 더 복잡한 문장(및 더 복잡한 문법 규칙)의 경우 모델은 각 단어를 적절하게 번역하기 위해 문장에서 더 멀리 나타날 수 있는 단어에 특별한 주의를 기울여야 합니다.

 

The same concept applies to any task associated with natural language: a word by itself has a meaning, but that meaning is deeply affected by the context, which can be any other word (or words) before or after the word being studied.

Now that you have an idea of what attention layers are all about, let’s take a closer look at the Transformer architecture.

 

동일한 개념이 자연어와 관련된 모든 작업에 적용됩니다. 단어 자체에는 의미가 있지만 해당 의미는 연구되는 단어 전후의 다른 단어(또는 단어)일 수 있는 문맥에 의해 깊은 영향을 받습니다.

이제 어텐션 레이어가 무엇인지 알았으니 Transformer 아키텍처를 자세히 살펴보겠습니다.

 

The original architecture

 

The Transformer architecture was originally designed for translation. During training, the encoder receives inputs (sentences) in a certain language, while the decoder receives the same sentences in the desired target language. In the encoder, the attention layers can use all the words in a sentence (since, as we just saw, the translation of a given word can be dependent on what is after as well as before it in the sentence). The decoder, however, works sequentially and can only pay attention to the words in the sentence that it has already translated (so, only the words before the word currently being generated). For example, when we have predicted the first three words of the translated target, we give them to the decoder which then uses all the inputs of the encoder to try to predict the fourth word.

 

Transformer 아키텍처는 원래 번역용으로 설계되었습니다. 학습 중에 인코더는 특정 언어로 된 입력(문장)을 수신하고 디코더는 원하는 대상 언어로 동일한 문장을 수신합니다. 인코더에서 어텐션 레이어는 문장의 모든 단어를 사용할 수 있습니다(방금 본 것처럼 주어진 단어의 번역은 문장의 앞과 뒤의 내용에 따라 달라질 수 있기 때문입니다). 그러나 디코더는 순차적으로 작동하며 이미 번역된 문장의 단어에만 주의를 기울일 수 있습니다. 즉, 현재 생성되고 있는 단어 앞의 단어에만 주의를 기울일 수 있습니다. 예를 들어, 번역된 대상의 처음 세 단어를 예측한 경우 이를 디코더에 제공하고 디코더는 인코더의 모든 입력을 사용하여 네 번째 단어를 예측하려고 시도합니다.

 

To speed things up during training (when the model has access to target sentences), the decoder is fed the whole target, but it is not allowed to use future words (if it had access to the word at position 2 when trying to predict the word at position 2, the problem would not be very hard!). For instance, when trying to predict the fourth word, the attention layer will only have access to the words in positions 1 to 3.

 

훈련 중에 작업 속도를 높이기 위해(모델이 대상 문장에 액세스할 수 있는 경우) 디코더에 전체 대상이 제공되지만 미래 단어를 사용할 수는 없습니다(예측을 시도할 때 위치 2의 단어에 액세스한 경우). 위치 2에 단어가 있으면 문제는 그리 어렵지 않을 것입니다!). 예를 들어, 네 번째 단어를 예측하려고 할 때 Attention 레이어는 위치 1~3의 단어에만 접근할 수 있습니다.

 

The original Transformer architecture looked like this, with the encoder on the left and the decoder on the right:

 

원래 Transformer 아키텍처는 다음과 같았습니다. 인코더는 왼쪽에 디코더는 오른쪽에 있습니다.

 

 

Note that the first attention layer in a decoder block pays attention to all (past) inputs to the decoder, but the second attention layer uses the output of the encoder. It can thus access the whole input sentence to best predict the current word. This is very useful as different languages can have grammatical rules that put the words in different orders, or some context provided later in the sentence may be helpful to determine the best translation of a given word.

 

디코더 블록의 첫 번째 attention layer 는 디코더에 대한 모든(과거) 입력에 주의를 기울이지만 두 번째 attention layer  인코더의 출력을 사용합니다. 따라서 전체 입력 문장에 액세스하여 현재 단어를 가장 잘 예측할 수 있습니다. 이는 다양한 언어가 단어의 순서를 다르게 지정하는 문법 규칙을 가질 수 있거나 문장의 뒷부분에 제공되는 일부 컨텍스트가 특정 단어의 최상의 번역을 결정하는 데 도움이 될 수 있으므로 매우 유용합니다.

 

The attention mask can also be used in the encoder/decoder to prevent the model from paying attention to some special words — for instance, the special padding word used to make all the inputs the same length when batching together sentences.

 

어텐션 마스크는 모델이 일부 특수 단어(예: 문장을 일괄 처리할 때 모든 입력을 동일한 길이로 만드는 데 사용되는 특수 패딩 단어)에 주의를 기울이는 것을 방지하기 위해 인코더/디코더에서 사용할 수도 있습니다.

 

Architectures vs. checkpoints

As we dive into Transformer models in this course, you’ll see mentions of architectures and checkpoints as well as models. These terms all have slightly different meanings:

 

이 과정에서 Transformer 모델을 자세히 살펴보면 모델뿐만 아니라 아키텍처와 체크포인트에 대한 언급도 볼 수 있습니다. 이러한 용어는 모두 약간 다른 의미를 갖습니다.

 

  • 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. This course will specify architecture or checkpoint when it matters to reduce ambiguity.

  • 모델: 이는 "아키텍처"나 "체크포인트"만큼 정확하지 않은 포괄적인 용어입니다. 두 가지 모두를 의미할 수 있습니다. 이 과정에서는 모호성을 줄이는 것이 중요한 경우 아키텍처 또는 체크포인트를 지정합니다.

For example, BERT is an architecture while bert-base-cased, a set of weights trained by the Google team for the first release of BERT, is a checkpoint. However, one can say “the BERT model” and “the bert-base-cased model.”

 

예를 들어, BERT는 아키텍처인 반면 Google 팀이 BERT의 첫 번째 릴리스를 위해 훈련한 가중치 세트인 bert-base-cased는 체크포인트입니다. 그러나 "BERT 모델"과 "bert-base-cased 모델"이라고 말할 수 있습니다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

반응형


반응형

 

Hugging Face provides a powerful and user-friendly API for working with natural language processing (NLP) models. The Hugging Face Transformers library is widely used for accessing and fine-tuning state-of-the-art pre-trained models.

 

Hugging Face는 자연어 처리(NLP) 모델 작업을 위한 강력하고 사용자 친화적인 API를 제공합니다. Hugging Face Transformers 라이브러리는 사전 훈련된 최첨단 모델에 액세스하고 미세 조정하는 데 널리 사용됩니다.

 

To get started with the Hugging Face API, you can follow these general steps:

 

Hugging Face API를 시작하려면 다음과 같은 일반적인 단계를 따르세요.

 

  1. Install Hugging Face Transformers: You can install the library using pip:

허깅 페이스 트랜스포머를 설치하세요: pip를 사용하여 라이브러리를 설치할 수 있습니다.

 

pip install transformers

 

2. Use Pre-trained Models:

Hugging Face offers a large collection of pre-trained models. You can easily use them for various NLP tasks. For example, using a pre-trained GPT-3 model:

 

Hugging Face는 사전 훈련된 모델의 대규모 컬렉션을 제공합니다. 다양한 NLP 작업에 쉽게 사용할 수 있습니다. 예를 들어 사전 훈련된 GPT-3 모델을 사용하면 다음과 같습니다.

 

from transformers import GPT2Model, GPT2Tokenizer

model = GPT2Model.from_pretrained("gpt2")
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")

# Example usage
input_text = "Hugging Face is making it easy to use NLP models."
input_ids = tokenizer.encode(input_text, return_tensors="pt")
outputs = model(input_ids)

 

3. Fine-tuning Models:

If you have a specific task and need to fine-tune a pre-trained model, you can do so using the Trainer module. Make sure to check the documentation for your specific use case.

 

특정 작업이 있고 사전 훈련된 모델을 미세 조정해야 하는 경우 트레이너 모듈을 사용하여 그렇게 할 수 있습니다. 특정 사용 사례에 대한 설명서를 확인하세요.

 

from transformers import GPT2ForSequenceClassification, GPT2Tokenizer, Trainer, TrainingArguments

model = GPT2ForSequenceClassification.from_pretrained("gpt2")
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")

# Set up your dataset and training arguments
# ...

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=train_dataset,
    eval_dataset=eval_dataset,
)

# Train the model
trainer.train()

 

 

4. Explore Datasets:

Hugging Face also provides access to various datasets for NLP tasks. You can easily load datasets for your specific task using the datasets library.

 

Hugging Face는 NLP 작업을 위한 다양한 데이터 세트에 대한 액세스도 제공합니다. 데이터세트 라이브러리를 사용하면 특정 작업에 대한 데이터세트를 쉽게 로드할 수 있습니다.

 

from datasets import load_dataset

dataset = load_dataset("imdb")

 

5. Model Deployment:

If you want to deploy your model, you can use the transformers-cli or other deployment methods. Hugging Face also provides a model hub for sharing and discovering models.

 

모델을 배포하려면 Transformers-cli 또는 기타 배포 방법을 사용할 수 있습니다. Hugging Face는 모델을 공유하고 검색할 수 있는 모델 허브도 제공합니다.

 

transformers-cli login
transformers-cli upload path/to/model

 

These are just basic steps to get started with the Hugging Face API. Depending on your specific use case, you might need to explore more advanced features and functionalities provided by the library. Refer to the official documentation for comprehensive information: Hugging Face Transformers Documentation.

 

이는 Hugging Face API를 시작하기 위한 기본 단계일 뿐입니다. 특정 사용 사례에 따라 라이브러리에서 제공하는 고급 기능을 탐색해야 할 수도 있습니다. 포괄적인 정보는 공식 문서인 Hugging Face Transformers 문서를 참조하세요.

 

 

 

 

 

반응형