Transformers documentation

ByT5

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

이 모델은 2021-05-28에 HF papers에 게시되었으며, 2021-06-01에 Hugging Face Transformers에 기여되었습니다.

ByT5

ByT5는 T5 모델의 토크나이저가 없는 버전으로, 원시 UTF-8 바이트를 직접 처리하도록 설계되었습니다. 이를 통해 모든 언어를 처리할 수 있으며, 오타와 같은 노이즈에 더 강건하고, 전처리 파이프라인이 필요하지 않아 사용이 더 간단합니다.

모든 원본 ByT5 체크포인트는 Google 조직에서 찾을 수 있습니다.

ByT5를 다양한 언어 작업에 적용하는 방법에 대한 추가 예제는 T5 문서를 참조하세요.

아래 예제는 Pipeline, AutoModel 및 명령줄을 사용하여 텍스트를 생성하는 방법을 보여줍니다.

AutoModel
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer


tokenizer = AutoTokenizer.from_pretrained(
    "google/byt5-small"
)
model = AutoModelForSeq2SeqLM.from_pretrained(
    "google/byt5-small",
    device_map="auto"
)

input_ids = tokenizer("summarize: Photosynthesis is the process by which plants, algae, and some bacteria convert light energy into chemical energy.", return_tensors="pt").to(model.device)

output = model.generate(**input_ids)
print(tokenizer.decode(output[0], skip_special_tokens=True))

양자화

Quantization은 가중치를 더 낮은 정밀도로 표현하여 대규모 모델의 메모리 부담을 줄입니다. 사용 가능한 다른 양자화 백엔드에 대해서는 Quantization 개요를 참조하세요.

아래 예제는 torchao를 사용하여 가중치만 int4로 양자화합니다.

# pip install torchao
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, TorchAoConfig


quantization_config = TorchAoConfig("int4_weight_only", group_size=128)

model = AutoModelForSeq2SeqLM.from_pretrained(
    "google/byt5-xl",
    device_map="auto",
    quantization_config=quantization_config
)

tokenizer = AutoTokenizer.from_pretrained("google/byt5-xl")
input_ids = tokenizer("translate English to French: The weather is nice today.", return_tensors="pt").to(model.device)

output = model.generate(**input_ids)
print(tokenizer.decode(output[0], skip_special_tokens=True))

The input is a single word "Notes". 참고

  • 토크나이저를 배치 추론 및 학습에 사용하는 것이 권장됩니다.

  • 아래 예시는 토크나이저 없이 모델을 사용하는 방법을 보여줍니다.

    import torch
    from transformers import AutoModelForSeq2SeqLM
    
    model = AutoModelForSeq2SeqLM.from_pretrained("google/byt5-small", device_map="auto")
    
    num_special_tokens = 3
    
    input_ids = torch.tensor([list("Life is like a box of chocolates.".encode("utf-8"))]) + num_special_tokens
    labels = torch.tensor([list("La vie est comme une boîte de chocolat.".encode("utf-8"))]) + num_special_tokens
    loss = model(input_ids, labels=labels).loss
    loss.item()
  • ByT5는 {extra_id_0}와 같은 sentinel token 대신 마스킹을 위해 상위 바이트 값(258, 257 등)을 사용합니다.

    # Example: character-level denoising with mask tokens
    input_ids = tokenizer("The dog chases a ball in the park.").input_ids
    masked_input = torch.tensor([input_ids[:8] + [258] + input_ids[14:21] + [257] + input_ids[28:]])
    output = model.generate(masked_input, max_length=100)

ByT5Tokenizer

클래스 transformers.ByT5Tokenizer

< >

( eos_token = '</s>'unk_token = '<unk>'pad_token = '<pad>'extra_ids = 125additional_special_tokens = None**kwargs )

매개변수

  • eos_token (str, 선택 사항, 기본값은 "</s>") — 시퀀스 종료 토큰입니다. 특수 토큰을 사용하여 시퀀스를 구성할 때, 시퀀스 종료에 사용되는 토큰은 이 토큰이 아닙니다. 시퀀스 종료에 사용되는 토큰은 sep_token입니다.

    특수 토큰을 사용하여 시퀀스를 구성할 때, 시퀀스 끝에는 이 토큰이 사용되지 않습니다. 사용되는 토큰은 sep_token입니다.

  • unk_token (str, 선택 사항, 기본값 "<unk>") — 미지의 토큰입니다. 어휘에 없는 토큰은 ID로 변환할 수 없으므로, 대신 이 토큰으로 설정됩니다.
  • pad_token (str, 선택 사항, 기본값 "<pad>") — 패딩에 사용되는 토큰입니다. 예를 들어, 길이가 다른 시퀀스를 배치(batching)할 때 사용됩니다.
  • extra_ids (int, 선택 사항, 기본값 125) — 사전 끝에 센티널로 사용될 추가 id의 수를 추가합니다. 이러한 토큰은 “<extraid{%d}>”로 접근할 수 있으며, 여기서 “{%d}”는 0부터 extra_ids-1 사이의 숫자입니다. 추가 토큰은 사전의 끝에서부터 시작까지 인덱싱됩니다(“<extra_id_0>”는 사전의 마지막 토큰이며, ByT5 전처리와 같습니다. 자세한 내용은 여기를 참조하세요).
  • additional_special_tokens (list[str], 선택) — 토크나이저에서 사용하는 추가 특수 토큰입니다.

ByT5 토크나이저를 구성합니다. ByT5는 단순히 원시 바이트의 utf-8 인코딩을 사용합니다.

이 토크나이저는 대부분의 주요 메서드를 포함하는 PreTrainedTokenizer를 상속합니다. 해당 메서드에 대한 자세한 내용은 이 상위 클래스를 참고하세요.

build_inputs_with_special_tokens

< >

( token_ids_0: list[int]token_ids_1: list[int] | None = None ) → list[int]

매개변수

  • token_ids_0 (list[int]) — 특별 토큰이 추가될 ID 목록입니다.
  • token_ids_1 (list[int], 선택 사항) — 시퀀스 쌍을 위한 선택적 두 번째 ID 목록입니다.

반환값

list[int]

적절한 특수 토큰이 포함된 입력 ID 목록

시퀀스 분류 작업을 위해 시퀀스 하나 또는 시퀀스 쌍을 연결하고 특수 토큰을 추가하여 모델 입력을 구성합니다. 시퀀스는 다음 형식을 가집니다:

  • 단일 시퀀스: X </s>
  • 시퀀스 쌍: A </s> B </s>

convert_tokens_to_string

< >

( tokens )

단일 문자열 내 토큰(문자열) 시퀀스를 변환합니다.

create_token_type_ids_from_sequences

< >

( token_ids_0: list[int]token_ids_1: list[int] | None = None ) → list[int]

매개변수

  • token_ids_0 (list[int]) — ID 목록.
  • token_ids_1 (list[int], 선택 사항) — 시퀀스 쌍을 위한 선택적 두 번째 ID 목록입니다.

반환값

list[int]

0으로만 이루어진 리스트.

시퀀스-페어 분류 작업에 사용될 두 시퀀스로부터 마스크를 생성합니다. ByT5는 토큰 타입 ID를 사용하지 않으므로, 0의 리스트가 반환됩니다.

get_special_tokens_mask

< >

( token_ids_0: list[int]token_ids_1: list[int] | None = Nonealready_has_special_tokens: bool = False ) → list[int]

매개변수

  • token_ids_0 (list[int]) — ID 목록.
  • token_ids_1 (list[int], 선택 사항) — 시퀀스 쌍을 위한 선택적 두 번째 ID 목록입니다.
  • already_has_special_tokens (bool, 선택, 기본값 False) — 토큰 목록이 이미 모델의 특수 토큰으로 포맷되어 있는지 여부입니다.

반환값

list[int]

[0, 1] 범위의 정수 목록: 특수 토큰은 1, 시퀀스 토큰은 0.

특수 토큰이 추가되지 않은 토큰 목록에서 시퀀스 ID를 가져옵니다. 이 메서드는 토크나이저의 prepare_for_model 메서드를 사용하여 특수 토큰을 추가할 때 호출됩니다.

Update on GitHub