Transformers documentation

PEGASUS-X

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

이 모델은 2022-08-08에 HF papers에 게시되었으며, 2022-09-02에 Hugging Face Transformers에 기여되었습니다.

FlashAttention

PEGASUS-X

PEGASUS-X는 긴 입력 요약에 사용되는 인코더-디코더(시퀀스-투-시퀀스) transformer 모델입니다. Pegasus 모델을 확장하여 staggered block-local attention, global encoder tokens, 그리고 긴 텍스트 시퀀스에 대한 추가 사전 학습을 적용함으로써 최대 16,000개의 토큰까지의 입력을 처리할 수 있습니다. PEGASUS-X는 더 적은 매개변수를 사용하면서도 훨씬 더 큰 모델과 동등한 성능을 발휘합니다.

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

이 모델은 zphang에 의해 기여되었습니다.

PEGASUS-X 모델을 적용하여 다양한 언어 작업을 수행하는 방법에 대한 추가 예제는 오른쪽 사이드바의 PEGASUS-X 모델에서 확인하세요.

아래 예제는 Pipeline, AutoModel, 그리고 명령줄을 사용하여 텍스트를 요약하는 방법을 보여줍니다.

AutoModel
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer


tokenizer = AutoTokenizer.from_pretrained(
    "google/pegasus-x-large"
)
model = AutoModelForSeq2SeqLM.from_pretrained(
    "google/pegasus-x-large",
    device_map="auto",
)

input_text = """Plants are among the most remarkable and essential life forms on Earth, possessing a unique ability to produce their own food through a process known as photosynthesis. This complex biochemical process is fundamental not only to plant life but to virtually all life on the planet.
Through photosynthesis, plants capture energy from sunlight using a green pigment called chlorophyll, which is located in specialized cell structures called chloroplasts. In the presence of light, plants absorb carbon dioxide from the atmosphere through small pores in their leaves called stomata, and take in water from the soil through their root systems.
These ingredients are then transformed into glucose, a type of sugar that serves as a source of chemical energy, and oxygen, which is released as a byproduct into the atmosphere. The glucose produced during photosynthesis is not just used immediately; plants also store it as starch or convert it into other organic compounds like cellulose, which is essential for building their cellular structure.
This energy reserve allows them to grow, develop leaves, produce flowers, bear fruit, and carry out various physiological processes throughout their lifecycle."""
input_ids = tokenizer(input_text, return_tensors="pt").to(model.device)

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

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

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

from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, BitsAndBytesConfig


quantization_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4"
)
model = AutoModelForSeq2SeqLM.from_pretrained(
    "google/pegasus-x-large",
    device_map="auto",
    quantization_config=quantization_config
)

tokenizer = AutoTokenizer.from_pretrained(
    "google/pegasus-x-large"
)

input_text = """Plants are among the most remarkable and essential life forms on Earth, possessing a unique ability to produce their own food through a process known as photosynthesis. This complex biochemical process is fundamental not only to plant life but to virtually all life on the planet.
Through photosynthesis, plants capture energy from sunlight using a green pigment called chlorophyll, which is located in specialized cell structures called chloroplasts. In the presence of light, plants absorb carbon dioxide from the atmosphere through small pores in their leaves called stomata, and take in water from the soil through their root systems.
These ingredients are then transformed into glucose, a type of sugar that serves as a source of chemical energy, and oxygen, which is released as a byproduct into the atmosphere. The glucose produced during photosynthesis is not just used immediately; plants also store it as starch or convert it into other organic compounds like cellulose, which is essential for building their cellular structure.
This energy reserve allows them to grow, develop leaves, produce flowers, bear fruit, and carry out various physiological processes throughout their lifecycle."""
input_ids = tokenizer(input_text, return_tensors="pt").to(model.device)

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

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

PegasusXConfig

클래스 transformers.PegasusXConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0id2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Noneis_encoder_decoder: bool = Truevocab_size: int = 96103max_position_embeddings: int = 16384encoder_layers: int = 16encoder_ffn_dim: int = 4096encoder_attention_heads: int = 16decoder_layers: int = 16decoder_ffn_dim: int = 4096decoder_attention_heads: int = 16encoder_layerdrop: float | int = 0.0decoder_layerdrop: float | int = 0.0use_cache: bool = Trueactivation_function: str = 'gelu'd_model: int = 1024dropout: float | int = 0.1attention_dropout: float | int = 0.0activation_dropout: float | int = 0.0init_std: float = 0.02decoder_start_token_id: int | None = 0scale_embedding: bool = Truepad_token_id: int | None = 0eos_token_id: int | list[int] | None = 1forced_eos_token_id: int | list[int] | None = 1num_global_tokens: int = 32block_size: int = 512stagger_local_blocks: bool = Truetie_word_embeddings: bool = True )

매개변수

  • is_encoder_decoder (bool, 선택 사항, 기본값 True) — 모델이 인코더/디코더로 사용되는지 여부를 나타냅니다.
  • vocab_size (int, 선택 사항, 기본값 96103) — 모델의 어휘 크기입니다. input_ids로 표현할 수 있는 서로 다른 토큰의 수를 정의합니다.
  • max_position_embeddings (int, 선택 사항, 기본값 16384) — 이 모델이 사용될 수 있는 최대 시퀀스 길이입니다.
  • encoder_layers (int, 선택 사항, 기본값 16) — Transformer 인코더의 숨겨진 레이어 수입니다. 설정하지 않으면 num_layers와 동일한 값을 사용합니다.
  • encoder_ffn_dim (int, 선택 사항, 기본값 4096) — encoder의 “intermediate”(일반적으로 feed-forward라고도 함) 레이어의 차원입니다.
  • encoder_attention_heads (int, 선택 사항, 기본값 16) — Transformer 인코더의 각 어텐션 레이어에 사용할 어텐션 헤드 수입니다.
  • decoder_layers (int, 선택 사항, 기본값 16) — Transformer decoder의 숨겨진 레이어 수입니다. 설정하지 않으면 num_layers와 동일한 값을 사용합니다.
  • decoder_ffn_dim (int, 선택 사항, 기본값 4096) — decoder의 “intermediate”(일반적으로 feed-forward라고도 함) 레이어의 차원.
  • decoder_attention_heads (int, 선택 사항, 기본값 16) — Transformer decoder의 각 attention layer에 사용할 attention head 수입니다.
  • encoder_layerdrop (Union[float, int], 선택 사항, 기본값 0.0) — 인코더의 LayerDrop 확률입니다. 자세한 내용은 [LayerDrop 논문](https://huggingface.co/papers/1909.11556 참조)을 참고하세요.
  • decoder_layerdrop (Union[float, int], 선택 사항, 기본값 0.0) — 디코더의 LayerDrop 확률입니다. 자세한 내용은 [LayerDrop 논문](https://huggingface.co/papers/1909.11556 참조)을 참고하세요.
  • use_cache (bool, 선택 사항, 기본값 True) — 모델이 마지막 key/values attention을 반환할지 여부입니다(모든 모델에서 사용되지 않음). config.is_decoder=True인 경우 또는 모델이 decoder-only 생성 모델인 경우에만 관련이 있습니다.
  • activation_function (str, 선택 사항, 기본값 gelu) — 디코더에서 사용되는 비선형 활성화 함수(함수 또는 문자열)입니다. 예를 들어, "gelu", "relu", "silu" 등이 있습니다.
  • d_model (int, 선택 사항, 기본값 1024) — 인코더 레이어와 풀러 레이어의 크기입니다.
  • dropout (Union[float, int], 선택 사항, 기본값 0.1) — 모든 dropout 레이어에 적용할 비율입니다.
  • attention_dropout (Union[float, int], 선택 사항, 기본값 0.0) — Attention 확률에 적용할 dropout 비율입니다.
  • activation_dropout (Union[float, int], 선택 사항, 기본값 0.0) — 완전 연결 레이어 내부 활성화에 적용할 dropout 비율입니다.
  • init_std (float, 선택 사항, 기본값 0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.
  • decoder_start_token_id (int, 선택 사항, 기본값 0) — 인코더-디코더 모델이 bos와 다른 토큰으로 디코딩을 시작하는 경우, 해당 토큰의 id입니다.
  • scale_embedding (bool, 선택 사항, 기본값 True) — 임베딩을 sqrt(d_model)로 나누어 스케일링할지 여부입니다.
  • pad_token_id (int, 선택 사항, 기본값 0) — 어휘에서 패딩에 사용되는 토큰 ID입니다.
  • eos_token_id (Union[int, list[int]], 선택 사항, 기본값 1) — 어휘에서 스트림 종료에 사용되는 토큰 id입니다.
  • forced_eos_token_id (Union[int, list[int]], 선택, 기본값 1) — max_length에 도달했을 때 마지막 생성 토큰으로 강제할 토큰의 id입니다. 일반적으로 eos_token_id로 설정됩니다.
  • num_global_tokens (int, 선택, 기본값 128) — 인코더에 사용할 글로벌 토큰의 수
  • block_size (int, 선택 사항, 기본값 512) — 인코더 로컬 어텐션에 사용할 블록 크기입니다. 시퀀스 길이는 블록 크기의 정확한 배수여야 합니다. stagger_local_block이 True인 경우 block_size는 2의 배수여야 합니다
  • stagger_local_blocks (bool, 선택 사항, 기본값 True) — 모든 짝수 번째 local attention을 반 블록만큼 시프트할지 여부
  • tie_word_embeddings (bool, 선택, 기본값 True) — 모델의 tied_weights_keys 매핑에 따라 가중치 임베딩을 묶을지 여부.

이것은 PegasusXModel의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 Pegasus X 모델을 초기화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 초기화하면 google/pegasus-x-large와 유사한 설정이 생성됩니다.

Configuration 객체는 PreTrainedConfig를 상속하며 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 PreTrainedConfig의 문서를 참고하세요.

예:

>>> from transformers import PegasusXConfig, PegasusXModel

>>> # Initializing a PEGASUS google/pegasus-x-large style configuration
>>> configuration = PegasusXConfig()

>>> # Initializing a model (with random weights) from the google/pegasus-x-large style configuration
>>> model = PegasusXModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

PegasusXModel

클래스 transformers.PegasusXModel

< >

( config: PegasusXConfig )

매개변수

  • config (PegasusXConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 연관된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.

특정 헤드가 위에 없는 상태에서 원시 hidden-states를 출력하는 순수 Pegasus X Model입니다.

이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.

forward

< >

( input_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonedecoder_input_ids: typing.Optional[torch.Tensor] = Nonedecoder_attention_mask: typing.Optional[torch.Tensor] = Noneencoder_outputs: tuple[torch.Tensor] | None = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonedecoder_inputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Seq2SeqModelOutput or tuple(torch.Tensor)

매개변수

  • input_ids (torch.Tensor 의 shape (batch_size, sequence_length), , 선택 사항) — 어휘(input vocabulary)에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.

    AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.

    입력 ID란 무엇인가요?

  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

    어텐션 마스크란 무엇인가요?

  • decoder_input_ids (torch.LongTensor 형상이 (batch_size, target_sequence_length), 선택 사항) — 어휘(decoder input sequence)에서 decoder 입력 시퀀스 토큰의 인덱스입니다. 인덱스는 AutoTokenizer를 사용하여 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()을 참조하세요. decoder input ID란 무엇인가요? PEGASUS-X는 decoder_input_ids 생성의 시작 토큰으로 pad_token_id를 사용합니다. past_key_values를 사용하는 경우, 선택적으로 마지막 decoder_input_ids만 입력하면 됩니다(past_key_values 참조).

    AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.

    디코더 입력 ID란 무엇인가요?

    PEGASUS-X는 decoder_input_ids 생성의 시작 토큰으로 pad_token_id를 사용합니다. past_key_values를 사용하는 경우, 선택적으로 마지막 decoder_input_ids만 입력하면 됩니다(past_key_values 참조).

  • decoder_attention_mask (torch.LongTensor, shape (batch_size, target_sequence_length), 선택) — 기본 동작: decoder_input_ids의 pad 토큰을 무시하는 텐서를 생성합니다. 기본적으로 causal mask도 사용됩니다.
  • encoder_outputs (tuple[torch.Tensor], 선택 사항) — (last_hidden_state, 선택 사항: hidden_states, 선택 사항: attentions)으로 구성된 튜플입니다. last_hidden_state의 모양은 (batch_size, sequence_length, hidden_size), 선택 사항)이며, 인코더의 마지막 레이어 출력에서 생성된 hidden-states의 시퀀스입니다. 디코더의 cross-attention에 사용됩니다.
  • past_key_values (~cache_utils.Cache, 선택 사항) — 순차적 디코딩을 가속화할 수 있는 사전 계산된 hidden-states(self-attention 블록과 cross-attention 블록의 key 및 value). 일반적으로 이는 past_key_values 디코딩의 이전 단계에서 모델이 반환한 use_cache=True 또는 config.use_cache=True.

    입력으로 Cache 인스턴스만 허용되며, kv cache 가이드를 참고하세요. past_key_values가 전달되지 않으면 기본적으로 DynamicCache가 초기화됩니다.

    모델은 입력으로 제공된 것과 동일한 캐시 형식을 출력합니다.

    past_key_values를 사용하는 경우, 이 모델에 과거 키 값 상태가 제공되지 않은 input_ids만 입력해야 하며, 이때의 shape은 (batch_size, unprocessed_length)입니다. shape이 (batch_size, sequence_length)인 전체 input_ids를 입력하지 않습니다.

  • inputs_embeds (torch.Tensor, shape (batch_size, sequence_length, hidden_size), 선택) — input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델 내부의 임베딩 조회 행렬보다 input_ids 인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다.
  • decoder_inputs_embeds (torch.Tensor 형상 (batch_size, target_sequence_length, hidden_size), 선택 사항) — 선택적으로, decoder_input_ids 대신에 임베딩된 표현을 직접 전달할 수 있습니다. past_key_values 이 사용되면, 선택적으로 마지막 decoder_inputs_embeds 만 입력하면 됩니다(참고: past_key_values). 이는 decoder_input_ids 인덱스를 관련 벡터로 변환하는 방식을 모델의 내부 임베딩 조회 행렬보다 더 세밀하게 제어하려는 경우에 유용합니다.

    decoder_input_ids와 decoder_inputs_embeds가 모두 설정되지 않은 경우, decoder_inputs_embeds는 inputs_embeds의 값을 가져옵니다.

  • use_cache (bool, 선택 사항) — True로 설정하면 past_key_values 키 값 상태가 반환되며, 디코딩 속도를 높이는 데 사용할 수 있습니다( past_key_values 참조).

반환값

Seq2SeqModelOutput 또는 tuple(torch.Tensor)

torch.Tensor의 튜플 또는 Seq2SeqModelOutput입니다. return_dict=False가 전달되었거나 config.return_dict=False인 경우, 구성(PegasusXConfig)과 입력에 따라 다양한 요소를 포함합니다.

PegasusXModel의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.

이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신 Module 인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.

  • last_hidden_state (torch.Tensor, shape (batch_size, sequence_length, hidden_size)) — 모델의 decoder 마지막 레이어 출력의 hidden-state 시퀀스입니다.

    past_key_values가 사용되면, (batch_size, 1, hidden_size) 형태의 시퀀스의 마지막 hidden-state만 출력됩니다.

  • past_key_values (EncoderDecoderCache, 선택 사항, use_cache=True가 전달되었거나 config.use_cache=True인 경우 반환됨) — EncoderDecoderCache 인스턴스입니다. 자세한 내용은 kv 캐시 가이드를 참고하세요.

    순차적 디코딩을 가속화하는 데 사용할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록과 크로스 어텐션 블록의 key 및 value)를 포함합니다(입력 past_key_values 참조).

  • decoder_hidden_states (tuple(torch.Tensor), 선택 사항, output_hidden_states=True가 전달되거나 config.output_hidden_states=True인 경우 반환됨) — torch.Tensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩의 출력에 대한 것 1개 + 각 레이어의 출력에 대한 것 1개)로, 모양은 (batch_size, sequence_length, hidden_size)입니다.

    각 레이어 출력의 decoder hidden-states와 선택적인 초기 embedding 출력

  • decoder_attentions (tuple(torch.Tensor), 선택 사항, output_attentions=True가 전달되거나 config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된 torch.Tensor의 튜플로, 모양은 (batch_size, num_heads, sequence_length, sequence_length)입니다.

    self-attention 헤드에서 가중 평균을 계산하는 데 사용되는, attention softmax 이후의 decoder의 attention 가중치입니다.

  • cross_attentions (tuple(torch.Tensor), 선택 사항, output_attentions=True가 전달되었거나 config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된 torch.Tensor의 튜플로, 모양은 (batch_size, num_heads, sequence_length, sequence_length)입니다.

    decoder의 cross-attention 레이어에서 attention softmax를 적용한 후, cross-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention 가중치입니다.

  • encoder_last_hidden_state (torch.Tensor, shape (batch_size, sequence_length, hidden_size), 선택 사항) — 모델 인코더의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.

  • encoder_hidden_states (tuple(torch.Tensor), 선택 사항, output_hidden_states=True가 전달되었거나 config.output_hidden_states=True인 경우 반환됨) — torch.Tensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩의 출력에 대한 것 1개 + 각 레이어의 출력에 대한 것 1개)로, 모양은 (batch_size, sequence_length, hidden_size)입니다.

    각 레이어 출력의 인코더 hidden-states와 선택적인 초기 임베딩 출력.

  • encoder_attentions (tuple(torch.Tensor), 선택 사항, output_attentions=True가 전달되거나 config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된 torch.Tensor의 튜플로, 모양은 (batch_size, num_heads, sequence_length, sequence_length)입니다.

    self-attention 헤드에서 가중 평균을 계산하는 데 사용되는, attention softmax 이후의 인코더 attention 가중치입니다.

예:

>>> from transformers import AutoTokenizer, PegasusModel

>>> tokenizer = AutoTokenizer.from_pretrained("google/pegasus-x-large")
>>> model = PegasusModel.from_pretrained("google/pegasus-x-large")

>>> inputs = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt")
>>> decoder_inputs = tokenizer("Studies show that", return_tensors="pt")
>>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_inputs.input_ids)

>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 4, 1024]

PegasusXForConditionalGeneration

클래스 transformers.PegasusXForConditionalGeneration

< >

( config: PegasusXConfig )

매개변수

  • config (PegasusXConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 연관된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.

조건 생성(예: 요약)을 위한 PEGASUS-X.

이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.

forward

< >

( input_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonedecoder_input_ids: typing.Optional[torch.Tensor] = Nonedecoder_attention_mask: typing.Optional[torch.Tensor] = Noneencoder_outputs: tuple[torch.Tensor] | None = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonedecoder_inputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Seq2SeqLMOutput or tuple(torch.Tensor)

매개변수

  • input_ids (torch.Tensor 의 shape (batch_size, sequence_length), , 선택 사항) — 어휘(input vocabulary)에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.

    AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.

    입력 ID란 무엇인가요?

  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

    어텐션 마스크란 무엇인가요?

  • decoder_input_ids (torch.LongTensor 형상이 (batch_size, target_sequence_length), 선택 사항) — 어휘(decoder input sequence)에서 decoder 입력 시퀀스 토큰의 인덱스입니다. 인덱스는 AutoTokenizer를 사용하여 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()을 참조하세요. decoder input ID란 무엇인가요? PEGASUS-X는 decoder_input_ids 생성의 시작 토큰으로 pad_token_id를 사용합니다. past_key_values를 사용하는 경우, 선택적으로 마지막 decoder_input_ids만 입력하면 됩니다(past_key_values 참조).

    AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.

    디코더 입력 ID란 무엇인가요?

    PEGASUS-X는 decoder_input_ids 생성의 시작 토큰으로 pad_token_id를 사용합니다. past_key_values를 사용하는 경우, 선택적으로 마지막 decoder_input_ids만 입력하면 됩니다(past_key_values 참조).

  • decoder_attention_mask (torch.LongTensor, shape (batch_size, target_sequence_length), 선택) — 기본 동작: decoder_input_ids의 pad 토큰을 무시하는 텐서를 생성합니다. 기본적으로 causal mask도 사용됩니다.
  • encoder_outputs (tuple[torch.Tensor], 선택 사항) — (last_hidden_state, 선택 사항: hidden_states, 선택 사항: attentions)으로 구성된 튜플입니다. last_hidden_state의 모양은 (batch_size, sequence_length, hidden_size), 선택 사항)이며, 인코더의 마지막 레이어 출력에서 생성된 hidden-states의 시퀀스입니다. 디코더의 cross-attention에 사용됩니다.
  • past_key_values (~cache_utils.Cache, 선택 사항) — 순차적 디코딩을 가속화할 수 있는 사전 계산된 hidden-states(self-attention 블록과 cross-attention 블록의 key 및 value). 일반적으로 이는 past_key_values 디코딩의 이전 단계에서 모델이 반환한 use_cache=True 또는 config.use_cache=True.

    입력으로 Cache 인스턴스만 허용되며, kv cache 가이드를 참고하세요. past_key_values가 전달되지 않으면 기본적으로 DynamicCache가 초기화됩니다.

    모델은 입력으로 제공된 것과 동일한 캐시 형식을 출력합니다.

    past_key_values를 사용하는 경우, 이 모델에 과거 키 값 상태가 제공되지 않은 input_ids만 입력해야 하며, 이때의 shape은 (batch_size, unprocessed_length)입니다. shape이 (batch_size, sequence_length)인 전체 input_ids를 입력하지 않습니다.

  • inputs_embeds (torch.Tensor, shape (batch_size, sequence_length, hidden_size), 선택) — input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델 내부의 임베딩 조회 행렬보다 input_ids 인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다.
  • decoder_inputs_embeds (torch.Tensor 형상 (batch_size, target_sequence_length, hidden_size), 선택 사항) — 선택적으로, decoder_input_ids 대신에 임베딩된 표현을 직접 전달할 수 있습니다. past_key_values 이 사용되면, 선택적으로 마지막 decoder_inputs_embeds 만 입력하면 됩니다(참고: past_key_values). 이는 decoder_input_ids 인덱스를 관련 벡터로 변환하는 방식을 모델의 내부 임베딩 조회 행렬보다 더 세밀하게 제어하려는 경우에 유용합니다.

    decoder_input_ids와 decoder_inputs_embeds가 모두 설정되지 않은 경우, decoder_inputs_embeds는 inputs_embeds의 값을 가져옵니다.

  • labels (torch.LongTensor, shape (batch_size, sequence_length), 선택 사항) — 마스크 언어 모델링 손실을 계산하는 데 사용되는 라벨입니다. 인덱스는 [0, ..., config.vocab_size] 범위 내의 값이거나 -100이어야 합니다(input_ids docstring 참조). 인덱스가 -100으로 설정된 토큰은 무시(마스크)되며, 손실은 [0, ..., config.vocab_size] 범위의 라벨을 가진 토큰에 대해서만 계산됩니다.
  • use_cache (bool, 선택 사항) — True로 설정하면 past_key_values 키 값 상태가 반환되며, 디코딩 속도를 높이는 데 사용할 수 있습니다( past_key_values 참조).

반환값

Seq2SeqLMOutput 또는 tuple(torch.Tensor)

torch.Tensor의 튜플 또는 Seq2SeqLMOutput입니다. return_dict=False가 전달되거나 config.return_dict=False인 경우, 구성(PegasusXConfig)과 입력에 따라 다양한 요소로 구성됩니다.

PegasusXForConditionalGeneration의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.

이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신 Module 인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.

  • loss (torch.Tensor, shape (1,), 선택 사항, labels이 제공될 때 반환됨) — 언어 모델링 손실.

  • logits (torch.Tensor, shape (batch_size, sequence_length, config.vocab_size)) — 언어 모델링 헤드에서 생성된 예측 점수(SoftMax 적용 전 각 어휘 토큰에 대한 점수).

  • past_key_values (EncoderDecoderCache, 선택 사항, use_cache=True가 전달되었거나 config.use_cache=True인 경우 반환됨) — EncoderDecoderCache 인스턴스입니다. 자세한 내용은 kv 캐시 가이드를 참고하세요.

    순차적 디코딩을 가속화하는 데 사용할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록과 크로스 어텐션 블록의 key 및 value)를 포함합니다(입력 past_key_values 참조).

  • decoder_hidden_states (tuple(torch.Tensor), 선택 사항, output_hidden_states=True가 전달되거나 config.output_hidden_states=True인 경우 반환됨) — torch.Tensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩의 출력에 대한 것 1개 + 각 레이어의 출력에 대한 것 1개)로, 모양은 (batch_size, sequence_length, hidden_size)입니다.

    각 레이어의 출력에서 디코더의 Hidden-states와 초기 임베딩 출력을 더한 값.

  • decoder_attentions (tuple(torch.Tensor), 선택 사항, output_attentions=True가 전달되거나 config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된 torch.Tensor의 튜플로, 모양은 (batch_size, num_heads, sequence_length, sequence_length)입니다.

    self-attention 헤드에서 가중 평균을 계산하는 데 사용되는, attention softmax 이후의 decoder의 attention 가중치입니다.

  • cross_attentions (tuple(torch.Tensor), 선택 사항, output_attentions=True가 전달되었거나 config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된 torch.Tensor의 튜플로, 모양은 (batch_size, num_heads, sequence_length, sequence_length)입니다.

    decoder의 cross-attention 레이어에서 attention softmax를 적용한 후, cross-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention 가중치입니다.

  • encoder_last_hidden_state (torch.Tensor, shape (batch_size, sequence_length, hidden_size), 선택 사항) — 모델 인코더의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.

  • encoder_hidden_states (tuple(torch.Tensor), 선택 사항, output_hidden_states=True가 전달되었거나 config.output_hidden_states=True인 경우 반환됨) — torch.Tensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩의 출력에 대한 것 1개 + 각 레이어의 출력에 대한 것 1개)로, 모양은 (batch_size, sequence_length, hidden_size)입니다.

    각 레이어의 출력에서 인코더의 Hidden-states와 초기 임베딩 출력을 더한 값.

  • encoder_attentions (tuple(torch.Tensor), 선택 사항, output_attentions=True가 전달되거나 config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된 torch.Tensor의 튜플로, 모양은 (batch_size, num_heads, sequence_length, sequence_length)입니다.

    self-attention 헤드에서 가중 평균을 계산하는 데 사용되는, attention softmax 이후의 인코더 attention 가중치입니다.

Update on GitHub