Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 2개 있습니다.)
스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
; https://www.sysnet.pe.kr/2/0/13363

스크립트: 50. Transformers (신경망 언어모델 라이브러리) 강좌 - 2장 코드 실행 결과
; https://www.sysnet.pe.kr/2/0/13375




Transformers (신경망 언어모델 라이브러리) 강좌 - 2장 코드 실행 결과

다음의 강좌에서,

Transformers (신경망 언어모델 라이브러리) 강좌
; https://wikidocs.net/book/8056

2장의 내용에,

2장. 🤗Transformers 라이브러리 사용하기
; https://wikidocs.net/166794

포함된 코드를 구글 Colab (또는 local 환경)에서 수행한 결과를 나열해 봅니다. ^^




from transformers import AutoTokenizer, AutoModel

checkpoint = "distilbert-base-uncased-finetuned-sst-2-english" # https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = AutoModel.from_pretrained(checkpoint)

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)

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

# 실행 결과
{'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]])}
torch.Size([2, 16, 768])

# 배치 크기(Batch size) == 2
# 시퀀스 길이(Sequence length) == 16 (len(inputs['input_ids'][0]))
# 은닉 크기(Hidden size) == 768

한글로 시도해 보려고 찾아낸 "quantumaikr/KoreanLM" 모델로는 (RAM의 제약으로) Colab에서 실습할 수 없습니다. (무료인 경우 Colab은 12GB 메모리를 주지만 아래의 코드를 실습하려면 34GB 정도의 여유 메모리가 필요합니다.) 따라서 한글용 코드를 실습하려면 별도의 환경을 구성해야 합니다. (제 경우에는 윈도우 환경의 PC에서 pytorch + transformer를 구성해 테스트했습니다.)

# https://huggingface.co/quantumaikr/KoreanLM

from transformers import AutoTokenizer, AutoModel

checkpoint = "quantumaikr/KoreanLM"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = AutoModel.from_pretrained(checkpoint)

raw_inputs = [
    "KoreanLM은 괜찮은 오픈소스 프로젝트입니다.",
    "그렇긴 해도 예제 코드를 Colab에서 수행하지 못할 정도로 많은 RAM을 요구합니다.",
]

inputs = tokenizer(raw_inputs, padding=True, truncation=True, return_tensors="pt")
print(inputs)

del inputs['token_type_ids']

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

# 출력 결과
{'input_ids': tensor([[    1, 22467, 26369, 31354, 29871,   237,   183,   159,   239,   179,
           177, 31354, 29871, 31346,   240,   151,   139, 31189, 30784, 29871,
           240,   151,   135, 30906,   239,   163,   160, 31177,   239,   161,
           136, 31063, 30709, 29889,     0,     0,     0,     0,     0,     0,
             0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
             0,     0,     0,     0,     0,     0,     0,     0,     0],
        [    1, 29871, 31607,   238,   163,   138,   237,   187,   183, 29871,
         31435, 31136, 29871,   239,   155,   139, 31306, 29871,   239,   192,
           151, 31493, 31517,  1530,   370, 31054, 31093, 29871, 30970,   240,
           153,   140, 30944, 30811, 29871,   238,   173,   190,   240,   152,
           163, 29871, 30852, 31136, 30906, 29871,   238,   170,   145, 31354,
         18113, 31286, 29871, 31527, 31231, 31980, 31063, 30709, 29889]]), 'token_type_ids': tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 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,
         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])}
torch.Size([2, 59, 4096])

참고로, "quantumaikr/KoreanLM" 모델은 tokenizer의 결과에 ('token_type_ids' 항목이 추가로 나와 이런 오류가 발생합니다. (예를 들어, DistilBERT 모델을 사용하는 경우에는 tokenizer가 token_type_ids를 반환하지 않음)

Traceback (most recent call last):
  File "C:\python\llml\test\sc1.py", line 15, in <module>
    outputs = model(**inputs)
  File "C:\python\llml\test\lib\site-packages\torch\nn\modules\module.py", line 1501, in _call_impl
    return forward_call(*args, **kwargs)
TypeError: LlamaModel.forward() got an unexpected keyword argument 'token_type_ids'

그래서 영문을 테스트했던 "distilbert-base-uncased-finetuned-sst-2-english"와는 달리 위의 코드에서는 "del inputs['token_type_ids']" 삭제 과정을 추가했습니다.




from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch

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

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)

outputs = model(**inputs)

print('outputs.logits.shape', outputs.logits.shape)
print('outputs.logits', outputs.logits)

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

print('model.config.id2label', model.config.id2label)

# 출력 결과
{'input_ids': ...[생략]..., 'attention_mask': ...[생략]...}
outputs.logits.shape torch.Size([2, 2])
outputs.logits tensor([[-1.5607,  1.6123],
        [ 4.1692, -3.3464]], grad_fn=<AddmmBackward0>)
predictions tensor([[4.0195e-02, 9.5980e-01],
        [9.9946e-01, 5.4418e-04]], grad_fn=<SoftmaxBackward0>)
model.config.id2label {0: 'NEGATIVE', 1: 'POSITIVE'}

from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch

checkpoint = "quantumaikr/KoreanLM"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = AutoModelForSequenceClassification.from_pretrained(checkpoint)

raw_inputs = [
    "KoreanLM은 괜찮은 오픈소스 프로젝트입니다.",
    "그렇긴 해도 예제 코드를 Colab에서 수행하지 못할 정도로 많은 RAM을 요구합니다.",
]

inputs = tokenizer(raw_inputs, padding=True, truncation=True, return_tensors="pt")
print(inputs)

del inputs['token_type_ids']

outputs = model(**inputs)

print('outputs.logits.shape', outputs.logits.shape)
print('outputs.logits', outputs.logits)

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

print('model.config.id2label', model.config.id2label)

# 출력 결과
{'input_ids': ...[생략]..., 'token_type_ids': ...[생략]..., 'attention_mask': ...[생략]...}
outputs.logits.shape torch.Size([2, 2])
outputs.logits tensor([[-0.2934,  1.9842],
        [-0.8308,  2.1648]], grad_fn=<IndexBackward0>)
predictions tensor([[0.0930, 0.9070],
        [0.0476, 0.9524]], grad_fn=<SoftmaxBackward0>)
model.config.id2label {0: 'LABEL_0', 1: 'LABEL_1'}




from transformers import BertConfig, BertModel

config = BertConfig()
print(config)

model = BertModel.from_pretrained("bert-base-cased")  # https://huggingface.co/bert-base-cased

# 출력 결과
BertConfig {
  "attention_probs_dropout_prob": 0.1,
  "classifier_dropout": null,
  "hidden_act": "gelu",
  "hidden_dropout_prob": 0.1,
  "hidden_size": 768,
  "initializer_range": 0.02,
  "intermediate_size": 3072,
  "layer_norm_eps": 1e-12,
  "max_position_embeddings": 512,
  "model_type": "bert",
  "num_attention_heads": 12,
  "num_hidden_layers": 12,
  "pad_token_id": 0,
  "position_embedding_type": "absolute",
  "transformers_version": "4.29.2",
  "type_vocab_size": 2,
  "use_cache": true,
  "vocab_size": 30522
}

from transformers import BertTokenizer, AutoTokenizer

bert_tokenizer = BertTokenizer.from_pretrained("bert-base-cased")
auto_tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")

print(bert_tokenizer)
print(auto_tokenizer)

print(bert_tokenizer("Using a Transformer network is simple"))
print(auto_tokenizer("Using a Transformer network is simple"))

tokens = bert_tokenizer.tokenize("Using a Transformer network is simple")  # subword tokenization
                                     # https://huggingface.co/bert-base-cased/blob/main/vocab.txt
print(tokens)

decoded_string = bert_tokenizer.decode([7993, 170, 13809, 23763, 2443, 1110, 3014])
print(decoded_string)

# 출력 결과
BertTokenizer(name_or_path='bert-base-cased', vocab_size=28996, model_max_length=512, is_fast=False, padding_side='right', truncation_side='right', special_tokens={'unk_token': '[UNK]', 'sep_token': '[SEP]', 'pad_token': '[PAD]', 'cls_token': '[CLS]', 'mask_token': '[MASK]'}, clean_up_tokenization_spaces=True)
BertTokenizerFast(name_or_path='bert-base-cased', vocab_size=28996, model_max_length=512, is_fast=True, padding_side='right', truncation_side='right', special_tokens={'unk_token': '[UNK]', 'sep_token': '[SEP]', 'pad_token': '[PAD]', 'cls_token': '[CLS]', 'mask_token': '[MASK]'}, clean_up_tokenization_spaces=True)

{'input_ids': [101, 7993, 170, 13809, 23763, 2443, 1110, 3014, 102], 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0], 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1]}
{'input_ids': [101, 7993, 170, 13809, 23763, 2443, 1110, 3014, 102], 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0], 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1]}

['Using', 'a', 'Trans', '##former', 'network', 'is', 'simple']

[7993, 170, 13809, 23763, 2443, 1110, 3014]

Using a Transformer network is simple




import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification

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

sequence = "I've been waiting for a HuggingFace course my whole life."

tokens = tokenizer.tokenize(sequence)
ids = tokenizer.convert_tokens_to_ids(tokens)
print("Input IDs:", ids)

input_ids = torch.tensor([ids])
print("Input IDs:", input_ids)

output = model(input_ids)
print("Logits:", output.logits)

# 출력 결과
Input IDs: [1045, 1005, 2310, 2042, 3403, 2005, 1037, 17662, 12172, 2607, 2026, 2878, 2166, 1012]
Input IDs: tensor([[ 1045,  1005,  2310,  2042,  3403,  2005,  1037, 17662, 12172,  2607,
          2026,  2878,  2166,  1012]])
Logits: tensor([[-2.7276,  2.8789]], grad_fn=<AddmmBackward0>)

import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification

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

sequence1_ids = [[200, 200, 200]]
sequence2_ids = [[200, 200]]
batched_ids = [
    [200, 200, 200],
    [200, 200, tokenizer.pad_token_id],
]

print(model(torch.tensor(sequence1_ids)).logits)
print(model(torch.tensor(sequence2_ids)).logits)
print(model(torch.tensor(batched_ids)).logits)

batch_ids = [
    [200, 200, 200],
    [200, 200, tokenizer.pad_token_id],
]

attention_mask = [
    [1, 1, 1],
    [1, 1, 0],
]
outputs = model(torch.tensor(batch_ids), attention_mask=torch.tensor(attention_mask))
print(outputs.logits)

# 출력 결과
tensor([[ 1.5694, -1.3895]], grad_fn=<AddmmBackward0>)
tensor([[ 0.5803, -0.4125]], grad_fn=<AddmmBackward0>)
tensor([[ 1.5694, -1.3895],
        [ 1.3374, -1.2163]], grad_fn=<AddmmBackward0>)
tensor([[ 1.5694, -1.3895],
        [ 0.5803, -0.4125]], grad_fn=<AddmmBackward0>)




from transformers import AutoTokenizer

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

sequences = ["I've been waiting for a HuggingFace course my whole life.", "So have I!"]

# 해당 시퀀스를 리스트 내의 최대 시퀀스 길이까지 패딩(padding) 합니다.
model_inputs = tokenizer(sequences, padding="longest")

# 시퀀스를 모델 최대 길이(model max length)까지 패딩(padding) 합니다.
# (512 for BERT or DistilBERT)
model_inputs = tokenizer(sequences, padding="max_length")

# 지정된 최대 길이까지 시퀀스를 패딩(padding) 합니다.
model_inputs = tokenizer(sequences, padding="max_length", max_length=8)

# 출력 결과
{'input_ids': [[101, 1045, 1005, 2310, 2042, 3403, 2005, 1037, 17662, 12172, 2607, 2026, 2878, 2166, 1012, 102], [101, 2061, 2031, 1045, 999, 102, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[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, 0, 0]]}

{'input_ids': [[101, 1045, 1005, 2310, 2042, 3403, 2005, 1037, 17662, 12172, 2607, 2026, 2878, 2166, 1012, 102, 0, 0, 0, ...[생략: max_length]..., 0, 0, 0, 0, 0], [101, 2061, 2031, 1045, 999, 102, 0, 0, 0, 0, ...[생략: max_length]..., 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, ...[생략: max_length]..., 0, 0, 0], [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...[생략: max_length]..., 0]]}

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

from transformers import AutoTokenizer

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

sequence = "I've been waiting for a HuggingFace course my whole life."

model_inputs = tokenizer(sequence)
print(model_inputs["input_ids"])

tokens = tokenizer.tokenize(sequence)
print(tokens)

ids = tokenizer.convert_tokens_to_ids(tokens)
print(ids)

print(tokenizer.decode(model_inputs["input_ids"]))
print(tokenizer.decode(ids))

# 출력 결과
[101, 1045, 1005, 2310, 2042, 3403, 2005, 1037, 17662, 12172, 2607, 2026, 2878, 2166, 1012, 102]
['i', "'", 've', 'been', 'waiting', 'for', 'a', 'hugging', '##face', 'course', 'my', 'whole', 'life', '.']
[1045, 1005, 2310, 2042, 3403, 2005, 1037, 17662, 12172, 2607, 2026, 2878, 2166, 1012]

[CLS] i've been waiting for a huggingface course my whole life. [SEP]
i've been waiting for a huggingface course my whole life.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 6/26/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 16  [17]  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13207정성태12/26/20224450.NET Framework: 2085. C# - gpedit.msc의 "User Rights Assignment" 특권을 코드로 설정/해제하는 방법파일 다운로드1
13206정성태12/24/20224683.NET Framework: 2084. C# - GetTokenInformation으로 사용자 SID(Security identifiers) 구하는 방법 [3]파일 다운로드1
13205정성태12/24/20224995.NET Framework: 2083. C# - C++과의 연동을 위한 구조체의 fixed 배열 필드 사용 (2)파일 다운로드1
13204정성태12/22/20224297.NET Framework: 2082. C# - (LSA_UNICODE_STRING 예제로) CustomMarshaler 사용법파일 다운로드1
13203정성태12/22/20224464.NET Framework: 2081. C# Interop 예제 - (LSA_UNICODE_STRING 예제로) 구조체를 C++에 전달하는 방법파일 다운로드1
13202정성태12/21/20224908기타: 84. 직렬화로 설명하는 Little/Big Endian파일 다운로드1
13201정성태12/20/20225490오류 유형: 835. PyCharm 사용 시 C 드라이브 용량 부족
13200정성태12/19/20224349오류 유형: 834. 이벤트 로그 - SSL Certificate Settings created by an admin process for endpoint
13199정성태12/19/20224603개발 환경 구성: 656. Internal Network 유형의 스위치로 공유한 Hyper-V의 VM과 호스트가 통신이 안 되는 경우
13198정성태12/18/20224506.NET Framework: 2080. C# - Microsoft.XmlSerializer.Generator 처리 없이 XmlSerializer 생성자를 예외 없이 사용하고 싶다면?파일 다운로드1
13197정성태12/17/20224417.NET Framework: 2079. .NET Core/5+ 환경에서 XmlSerializer 사용 시 System.IO.FileNotFoundException 예외 발생하는 경우파일 다운로드1
13196정성태12/16/20224574.NET Framework: 2078. .NET Core/5+를 위한 SGen(Microsoft.XmlSerializer.Generator) 사용법
13195정성태12/15/20225109개발 환경 구성: 655. docker - bridge 네트워크 모드에서 컨테이너 간 통신 시 --link 옵션 권장 이유
13194정성태12/14/20225138오류 유형: 833. warning C4747: Calling managed 'DllMain': Managed code may not be run under loader lock파일 다운로드1
13193정성태12/14/20225228오류 유형: 832. error C7681: two-phase name lookup is not supported for C++/CLI or C++/CX; use /Zc:twoPhase-
13192정성태12/13/20225236Linux: 55. 리눅스 - bash shell에서 실수 연산
13191정성태12/11/20226134.NET Framework: 2077. C# - 직접 만들어 보는 SynchronizationContext파일 다운로드1
13190정성태12/9/20226633.NET Framework: 2076. C# - SynchronizationContext 기본 사용법파일 다운로드1
13189정성태12/9/20227370오류 유형: 831. Visual Studio - Windows Forms 디자이너의 도구 상자에 컨트롤이 보이지 않는 문제
13188정성태12/9/20226094.NET Framework: 2075. C# - 직접 만들어 보는 TaskScheduler 실습 (SingleThreadTaskScheduler)파일 다운로드1
13187정성태12/8/20225989개발 환경 구성: 654. openssl - CA로부터 인증받은 새로운 인증서를 생성하는 방법 (2)
13186정성태12/6/20224541오류 유형: 831. The framework 'Microsoft.AspNetCore.App', version '...' was not found.
13185정성태12/6/20225519개발 환경 구성: 653. Windows 환경에서의 Hello World x64 어셈블리 예제 (NASM 버전)
13184정성태12/5/20224780개발 환경 구성: 652. ml64.exe와 link.exe x64 실행 환경 구성
13183정성태12/4/20224646오류 유형: 830. MASM + CRT 함수를 사용하는 경우 발생하는 컴파일 오류 정리
13182정성태12/4/20225376Windows: 217. Windows 환경에서의 Hello World x64 어셈블리 예제 (MASM 버전)
... 16  [17]  18  19  20  21  22  23  24  25  26  27  28  29  30  ...