Transformers documentation
T5Gemma 2
이 모델은 2025-12-01에 Hugging Face Transformers에 기여되었습니다.
T5Gemma 2
T5Gemma 2는 다국어, 멀티모달 및 긴 컨텍스트 처리 능력이 뛰어난 사전 학습된 인코더-디코더 대규모 언어 모델(LLM) 계열로, 270M-270M, 1B-1B, 4B-4B 파라미터 규모로 제공됩니다. T5Gemma를 이어받아 UL2를 기반으로 한 모델 적응(기반 모델: Gemma 3)을 통해 구축되었습니다. 아키텍처는 T5Gemma와 Gemma 3와 유사하며, 모델 파라미터 절약을 위해 tied word embeddings과 통합된 self-attention 및 cross-attention을 적용하여 강화되었습니다.
오른쪽 사이드바의 T5Gemma 2 모델에 클릭하여 T5Gemma 2를 다양한 언어 작업에 적용하는 방법에 대한 추가 예제를 확인하세요.
아래 예제는 Pipeline 또는 AutoModel 클래스를 사용하여 모델과 채팅하는 방법과 커맨드 라인에서 사용하는 방법을 보여줍니다.
from transformers import pipeline
generator = pipeline(
"image-text-to-text",
model="google/t5gemma-2-270m-270m",
device_map="auto",
)
generator(
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg",
text="<start_of_image> in this image, there is",
generate_kwargs={"do_sample": False, "max_new_tokens": 50},
)import requests
from PIL import Image
from transformers import AutoModelForSeq2SeqLM, AutoProcessor
processor = AutoProcessor.from_pretrained("google/t5gemma-2-270m-270m")
model = AutoModelForSeq2SeqLM.from_pretrained(
"google/t5gemma-2-270m-270m",
device_map="auto",
)
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg"
image = Image.open(requests.get(url, stream=True).raw)
prompt = "<start_of_image> in this image, there is"
model_inputs = processor(text=prompt, images=image, return_tensors="pt").to(model.device)
generation = model.generate(**model_inputs, max_new_tokens=20, do_sample=False)
print(processor.decode(generation[0]))T5Gemma2Config
클래스 transformers.T5Gemma2Config
< source >( 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 = Trueencoder: transformers.models.t5gemma2.configuration_t5gemma2.T5Gemma2EncoderConfig | dict[str, typing.Any] | None = Nonedecoder: transformers.models.t5gemma2.configuration_t5gemma2.T5Gemma2DecoderConfig | dict[str, typing.Any] | None = Nonedropout_rate: float | int = 0.0attention_dropout: float | int = 0.0classifier_dropout_rate: float | int = 0.0initializer_range: float = 0.02image_token_index: int = 256001eoi_token_index: int | None = Nonetie_word_embeddings: bool = True )
매개변수
- is_encoder_decoder (
bool, 선택 사항, 기본값True) — 모델이 인코더/디코더로 사용되는지 여부를 나타냅니다. - encoder (
Union[T5Gemma2EncoderConfig, dict], 선택 사항, 선택 사항) — 인코더에 대한 설정입니다. - decoder (
Union[T5Gemma2DecoderConfig, dict], optional, 선택 사항) — 디코더에 대한 설정입니다. - dropout_rate (
Union[float, int], 선택 사항, 기본값0.0) — 모든 dropout 레이어에 적용할 비율입니다. - attention_dropout (
Union[float, int], 선택 사항, 기본값0.0) — Attention 확률에 적용할 dropout 비율입니다. - classifier_dropout_rate (
Union[float, int], 선택, 기본값0.0) — classifier의 dropout 비율입니다. - initializer_range (
float, 선택 사항, 기본값0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다. - image_token_index (
int, 선택 사항, 기본값256001) — 입력 이미지용으로 플레이스홀더로 사용되는 이미지 토큰 인덱스입니다. - eoi_token_index (
int, 선택 사항) — 이미지 프롬프트를 감싸기 위한 end-of-image 토큰 인덱스입니다.self.encoder.eoi_token_index와 동일합니다. - tie_word_embeddings (
bool, 선택, 기본값True) — 모델의tied_weights_keys매핑에 따라 가중치 임베딩을 묶을지 여부.
This is the configuration class to store the configuration of a T5Gemma2Model. It is used to instantiate a T5Gemma2 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the google/t5gemma-2-270m-270m
Configuration 객체는 PreTrainedConfig를 상속하며 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 PreTrainedConfig의 문서를 참고하세요.
T5Gemma2TextConfig
클래스 transformers.T5Gemma2TextConfig
< source >( 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 = 0is_encoder_decoder: bool = Falseid2label: 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 = Nonevocab_size: int = 262208hidden_size: int = 2304intermediate_size: int = 9216num_hidden_layers: int = 26num_attention_heads: int = 8num_key_value_heads: int = 4head_dim: int = 256hidden_activation: str = 'gelu_pytorch_tanh'max_position_embeddings: int = 131072initializer_range: float = 0.02rms_norm_eps: float = 1e-06use_cache: bool = Truepad_token_id: int | None = 0eos_token_id: int | list[int] | None = 1bos_token_id: int | None = 2tie_word_embeddings: bool = Truerope_parameters: dict | None = Noneattention_bias: bool = Falseattention_dropout: int | float | None = 0.0query_pre_attn_scalar: int = 256sliding_window: int | None = 4096layer_types: list[str] | None = Nonefinal_logit_softcapping: float | None = Noneattn_logit_softcapping: float | None = None )
매개변수
- vocab_size (
int, 선택 사항, 기본값262208) — 모델의 어휘 크기입니다.input_ids로 표현할 수 있는 서로 다른 토큰의 수를 정의합니다. - hidden_size (
int, 선택 사항, 기본값2304) — 숨겨진 표현의 차원입니다. - intermediate_size (
int, 선택 사항, 기본값9216) — MLP 표현의 차원입니다. - num_hidden_layers (
int, 선택 사항, 기본값26) — Transformer decoder의 숨겨진 레이어 수. - num_attention_heads (
int, 선택 사항, 기본값8) — Transformer decoder의 각 attention layer에 사용할 attention head의 수입니다. - num_key_value_heads (
int, 선택 사항, 기본값4) — Grouped Query Attention 구현에 사용할 key_value 헤드 수입니다.num_key_value_heads=num_attention_heads이면 모델은 Multi Head Attention(MHA)을 사용하고,num_key_value_heads=1이면 Multi Query Attention(MQA)을 사용하며, 그 외에는 GQA를 사용합니다. 멀티 헤드 체크포인트를 GQA 체크포인트로 변환할 때, 각 그룹의 key 및 value 헤드는 해당 그룹 내 모든 원래 헤드를 평균 풀링(meanpooling)하여 구성해야 합니다. 자세한 내용은 이 논문을 참고하세요. 지정되지 않으면num_attention_heads가 기본값으로 사용됩니다. - head_dim (
int, 선택 사항, 기본값256) — Attention head의 차원입니다. None인 경우 hidden_size // num_attention_heads가 기본값으로 사용됩니다. - hidden_activation (
str, 선택 사항, 기본값gelu_pytorch_tanh) — 디코더에서 사용되는 비선형 활성화 함수(함수 또는 문자열)입니다. 예를 들어,"gelu","relu","silu"등이 있습니다. - max_position_embeddings (
int, 선택 사항, 기본값131072) — 이 모델이 사용될 수 있는 최대 시퀀스 길이입니다. - initializer_range (
float, 선택 사항, 기본값0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다. - rms_norm_eps (
float, 선택 사항, 기본값1e-06) — rms 정규화 레이어에서 사용되는 epsilon 값입니다. - use_cache (
bool, 선택 사항, 기본값True) — 모델이 마지막 key/values attention을 반환할지 여부입니다(모든 모델에서 사용되지 않음).config.is_decoder=True인 경우 또는 모델이 decoder-only 생성 모델인 경우에만 관련이 있습니다. - pad_token_id (
int, 선택 사항, 기본값0) — 어휘에서 패딩에 사용되는 토큰 ID입니다. - eos_token_id (
Union[int, list[int]], 선택 사항, 기본값1) — 어휘에서 스트림 종료에 사용되는 토큰 id입니다. - bos_token_id (
int, 선택 사항, 기본값2) — 어휘에서 스트림 시작에 사용되는 토큰 ID입니다. - tie_word_embeddings (
bool, 선택, 기본값True) — 모델의tied_weights_keys매핑에 따라 가중치 임베딩을 묶을지 여부. - rope_parameters (
dict, 선택) — RoPE 임베딩의 구성 매개변수를 포함하는 사전입니다. 사전에는rope_theta값이 포함되어야 하며, 더 긴max_position_embeddings로 RoPE를 사용하려는 경우 스케일링에 사용되는 매개변수를 선택적으로 포함할 수 있습니다. - attention_bias (
bool, 선택 사항, 기본값False) — 자기 주의(self-attention) 시 query, key, value 및 출력 투영 계층에 bias를 사용할지 여부입니다. - attention_dropout (
Union[int, float], 선택 사항, 기본값0.0) — Attention 확률에 적용할 dropout 비율입니다. - query_pre_attn_scalar (
float, 선택 사항, 기본값 256) — Attention score에 사용되는 스케일링 계수 - sliding_window (
int, 선택 사항, 기본값4096) — 슬라이딩 윈도우 어텐션의 윈도우 크기입니다.None인 경우 슬라이딩 윈도우가 적용되지 않습니다. - layer_types (
list[str], 선택 사항) — 각 레이어 인덱스를 해당 레이어 유형에 명시적으로 매핑하는 목록입니다. 제공되지 않으면 config 값에 기반하여 자동으로 생성됩니다. - final_logit_softcapping (
float, 선택 사항) — logits에 tanh softcapping을 적용할 때 사용할 스케일링 계수입니다. - attn_logit_softcapping (
float, 선택 사항) — Attention scores에 tanh softcapping을 적용할 때 사용하는 스케일링 계수입니다.
이것은 T5Gemma2Model의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 T5Gemma2 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 인스턴스화하면 google/t5gemma-2-270m-270m와 유사한 설정이 생성됩니다.
Configuration 객체는 PreTrainedConfig를 상속하며 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 PreTrainedConfig의 문서를 참고하세요.
T5Gemma2EncoderConfig
클래스 transformers.T5Gemma2EncoderConfig
< source >( 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 = 0is_encoder_decoder: bool = Falseid2label: 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 = Nonetext_config: transformers.configuration_utils.PreTrainedConfig | dict[str, typing.Any] | None = Nonevision_config: transformers.configuration_utils.PreTrainedConfig | dict[str, typing.Any] | None = Nonemm_tokens_per_image: int | None = 256boi_token_index: int | None = 255999eoi_token_index: int | None = 256000image_token_index: int | None = 262144initializer_range: float | None = 0.02tie_word_embeddings: bool | None = True )
매개변수
- text_config (
Union[~configuration_utils.PreTrainedConfig, dict[str, Any]], 선택) — 텍스트 백본의 config 객체 또는 사전입니다. - vision_config (
Union[~configuration_utils.PreTrainedConfig, dict[str, Any]], 선택) — 비전 백본의 config 객체 또는 사전입니다. - mm_tokens_per_image (
int, 선택, 기본값 256) — 이미지 임베딩당 토큰 수입니다. - boi_token_index (
int, 선택 사항, 기본값 255999) — 이미지 프롬프트를 감싸기 위한 begin-of-image 토큰 인덱스입니다. - eoi_token_index (
int, 선택 사항, 기본값 256000) — 이미지 프롬프트를 감싸기 위한 end-of-image 토큰 인덱스입니다. - image_token_index (
int, 선택 사항, 기본값262144) — 입력 이미지용으로 플레이스홀더로 사용되는 이미지 토큰 인덱스입니다. - initializer_range (
float, 선택 사항, 기본값0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다. - tie_word_embeddings (
bool, 선택, 기본값True) — 모델의tied_weights_keys매핑에 따라 가중치 임베딩을 묶을지 여부.
이것은 T5Gemma2Model의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 T5Gemma2 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 인스턴스화하면 google/t5gemma-2-270m-270m의 설정과 유사한 설정이 생성됩니다.
Configuration 객체는 PreTrainedConfig를 상속하며 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 PreTrainedConfig의 문서를 참고하세요.
예:
>>> from transformers import T5Gemma2EncoderForConditionalGeneration, T5Gemma2EncoderConfig, SiglipVisionConfig, T5Gemma2EncoderTextConfig
>>> # Initializing a Siglip-like vision config
>>> vision_config = SiglipVisionConfig()
>>> # Initializing a T5Gemma2Encoder Text config
>>> text_config = T5Gemma2EncoderTextConfig()
>>> # Initializing a T5Gemma2Encoder gemma-3-4b style configuration
>>> configuration = T5Gemma2EncoderConfig(vision_config, text_config)
>>> # Initializing a model from the gemma-3-4b style configuration
>>> model = T5Gemma2EncoderForConditionalGeneration(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configT5Gemma2DecoderConfig
클래스 transformers.T5Gemma2DecoderConfig
< source >( 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 = 0is_encoder_decoder: bool = Falseid2label: 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 = Nonevocab_size: int = 262208hidden_size: int = 2304intermediate_size: int = 9216num_hidden_layers: int = 26num_attention_heads: int = 8num_key_value_heads: int = 4head_dim: int = 256hidden_activation: str = 'gelu_pytorch_tanh'max_position_embeddings: int = 131072initializer_range: float = 0.02rms_norm_eps: float = 1e-06use_cache: bool = Truepad_token_id: int | None = 0eos_token_id: int | list[int] | None = 1bos_token_id: int | None = 2tie_word_embeddings: bool = Truerope_parameters: dict | None = Noneattention_bias: bool = Falseattention_dropout: int | float | None = 0.0query_pre_attn_scalar: int = 256sliding_window: int | None = 4096layer_types: list[str] | None = Nonefinal_logit_softcapping: float | None = Noneattn_logit_softcapping: float | None = None )
매개변수
- vocab_size (
int, 선택 사항, 기본값262208) — 모델의 어휘 크기입니다.input_ids로 표현할 수 있는 서로 다른 토큰의 수를 정의합니다. - hidden_size (
int, 선택 사항, 기본값2304) — 숨겨진 표현의 차원입니다. - intermediate_size (
int, 선택 사항, 기본값9216) — MLP 표현의 차원입니다. - num_hidden_layers (
int, 선택 사항, 기본값26) — Transformer decoder의 숨겨진 레이어 수. - num_attention_heads (
int, 선택 사항, 기본값8) — Transformer decoder의 각 attention layer에 사용할 attention head의 수입니다. - num_key_value_heads (
int, 선택 사항, 기본값4) — Grouped Query Attention 구현에 사용할 key_value 헤드 수입니다.num_key_value_heads=num_attention_heads이면 모델은 Multi Head Attention(MHA)을 사용하고,num_key_value_heads=1이면 Multi Query Attention(MQA)을 사용하며, 그 외에는 GQA를 사용합니다. 멀티 헤드 체크포인트를 GQA 체크포인트로 변환할 때, 각 그룹의 key 및 value 헤드는 해당 그룹 내 모든 원래 헤드를 평균 풀링(meanpooling)하여 구성해야 합니다. 자세한 내용은 이 논문을 참고하세요. 지정되지 않으면num_attention_heads가 기본값으로 사용됩니다. - head_dim (
int, 선택 사항, 기본값256) — Attention head의 차원입니다. None인 경우 hidden_size // num_attention_heads가 기본값으로 사용됩니다. - hidden_activation (
str, 선택 사항, 기본값gelu_pytorch_tanh) — 디코더에서 사용되는 비선형 활성화 함수(함수 또는 문자열)입니다. 예를 들어,"gelu","relu","silu"등이 있습니다. - max_position_embeddings (
int, 선택 사항, 기본값131072) — 이 모델이 사용될 수 있는 최대 시퀀스 길이입니다. - initializer_range (
float, 선택 사항, 기본값0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다. - rms_norm_eps (
float, 선택 사항, 기본값1e-06) — rms 정규화 레이어에서 사용되는 epsilon 값입니다. - use_cache (
bool, 선택 사항, 기본값True) — 모델이 마지막 key/values attention을 반환할지 여부입니다(모든 모델에서 사용되지 않음).config.is_decoder=True인 경우 또는 모델이 decoder-only 생성 모델인 경우에만 관련이 있습니다. - pad_token_id (
int, 선택 사항, 기본값0) — 어휘에서 패딩에 사용되는 토큰 ID입니다. - eos_token_id (
Union[int, list[int]], 선택 사항, 기본값1) — 어휘에서 스트림 종료에 사용되는 토큰 id입니다. - bos_token_id (
int, 선택 사항, 기본값2) — 어휘에서 스트림 시작에 사용되는 토큰 ID입니다. - tie_word_embeddings (
bool, 선택, 기본값True) — 모델의tied_weights_keys매핑에 따라 가중치 임베딩을 묶을지 여부. - rope_parameters (
dict, 선택) — RoPE 임베딩의 구성 매개변수를 포함하는 사전입니다. 사전에는rope_theta값이 포함되어야 하며, 더 긴max_position_embeddings로 RoPE를 사용하려는 경우 스케일링에 사용되는 매개변수를 선택적으로 포함할 수 있습니다. - attention_bias (
bool, 선택 사항, 기본값False) — 자기 주의(self-attention) 시 query, key, value 및 출력 투영 계층에 bias를 사용할지 여부입니다. - attention_dropout (
Union[int, float], 선택 사항, 기본값0.0) — Attention 확률에 적용할 dropout 비율입니다. - query_pre_attn_scalar (
float, 선택 사항, 기본값 256) — Attention scores에 사용되는 스케일링 계수 - sliding_window (
int, 선택 사항, 기본값4096) — 슬라이딩 윈도우 어텐션의 윈도우 크기입니다.None인 경우 슬라이딩 윈도우가 적용되지 않습니다. - layer_types (
list[str], 선택 사항) — 각 레이어 인덱스를 해당 레이어 유형에 명시적으로 매핑하는 목록입니다. 제공되지 않으면 config 값에 기반하여 자동으로 생성됩니다. - final_logit_softcapping (
float, 선택 사항) — logits에 tanh softcapping을 적용할 때 사용할 스케일링 계수입니다. - attn_logit_softcapping (
float, 선택 사항) — Attention scores에 tanh softcapping을 적용할 때 사용하는 스케일링 계수입니다.
This is the configuration class to store the configuration of a T5Gemma2Model. It is used to instantiate a T5Gemma2 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the google/t5gemma-2-270m-270m
Configuration 객체는 PreTrainedConfig를 상속하며 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 PreTrainedConfig의 문서를 참고하세요.
T5Gemma2Model
클래스 transformers.T5Gemma2Model
< source >( config: T5Gemma2Config )
매개변수
- config (T5Gemma2Config) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.
특정 헤드가 위에 없는 상태의 기본 T5Gemma2 모델은 원시 hidden-states를 출력합니다.
이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.
이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.FloatTensor] = Noneattention_mask: typing.Optional[torch.FloatTensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonedecoder_input_ids: typing.Optional[torch.LongTensor] = Nonedecoder_attention_mask: typing.Optional[torch.BoolTensor] = Nonedecoder_position_ids: typing.Optional[torch.LongTensor] = Noneencoder_outputs: transformers.modeling_outputs.BaseModelOutput | None = Nonepast_key_values: transformers.cache_utils.EncoderDecoderCache | 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.FloatTensor)
매개변수
- input_ids (
torch.LongTensor형상이(batch_size, sequence_length), 선택 사항) — 어휘(input vocabulary)에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.
- pixel_values (
torch.FloatTensor, shape(batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 Gemma3ImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 Gemma3ImageProcessor.call()를 참조하세요 (Gemma3Processor는 이미지 처리에 Gemma3ImageProcessor를 사용합니다). - attention_mask (
torch.FloatTensorshape(batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요?[0, 1]:- 마스크되지 않은 토큰에 대해 1
- 마스크된 토큰에 대해 0
- position_ids (
torch.LongTensor의 shape(batch_size, sequence_length), , 선택 사항) — 위치 임베딩에서 각 입력 시퀀스 토큰의 위치 인덱스. 범위[0, config.n_positions - 1]. - decoder_input_ids (
torch.LongTensor형상(batch_size, target_sequence_length), 선택 사항) — 어휘에서 디코더 입력 시퀀스 토큰의 인덱스입니다. AutoTokenizer를 사용하여 인덱스를 가져올 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()을 참조하세요. 디코더 입력 ID란 무엇인가요?AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.
- decoder_attention_mask (
torch.BoolTensor, shape(batch_size, target_sequence_length), 선택) — 특정 토큰 인덱스에 대한 attention을 수행하지 않도록 하는 mask입니다. 기본적으로 causal mask를 사용하여 모델이 미래를 예측할 때 이전 입력만 참조할 수 있도록 합니다. - decoder_position_ids (
torch.LongTensor, shape(batch_size, decoder_sequence_length), 선택 사항) — decoder 입력 시퀀스의 각 토큰이 position embeddings에서 차지하는 위치 인덱스입니다.[0, config.decoder.n_positions - 1]범위에서 선택됩니다. position ID란 무엇인가요? - encoder_outputs (
~modeling_outputs.BaseModelOutput, 선택 사항) — (last_hidden_state, 선택 사항:hidden_states, 선택 사항:attentions)의 Tuplelast_hidden_state의 shape은(batch_size, sequence_length, hidden_size), 선택 사항)이며, 인코더의 마지막 레이어 출력에서 생성된 hidden-states의 시퀀스입니다. 디코더의 cross-attention에 사용됩니다. - past_key_values (
~cache_utils.EncoderDecoderCache, 선택 사항) — 순차적 디코딩을 가속화할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록과 크로스 어텐션 블록의 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.FloatTensor)
torch.FloatTensor의 튜플 또는 Seq2SeqModelOutput입니다. return_dict=False가 전달되었거나 config.return_dict=False인 경우, T5Gemma2Config와 입력에 따라 다양한 요소를 포함합니다.
T5Gemma2Model의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.
이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신
Module인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.
last_hidden_state (
torch.FloatTensor, 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.FloatTensor), 선택,output_hidden_states=True가 전달되었거나config.output_hidden_states=True인 경우 반환됨) —torch.FloatTensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 형태는(batch_size, sequence_length, hidden_size)입니다.각 레이어 출력의 decoder hidden-states와 선택적인 초기 embedding 출력
decoder_attentions (
tuple(torch.FloatTensor), 선택 사항,output_attentions=True가 전달되었거나config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된torch.FloatTensor의 튜플로, 모양은(batch_size, num_heads, sequence_length, sequence_length)입니다.self-attention 헤드에서 가중 평균을 계산하는 데 사용되는, attention softmax 이후의 decoder의 attention 가중치입니다.
cross_attentions (
tuple(torch.FloatTensor), 선택 사항,output_attentions=True가 전달되었거나config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된torch.FloatTensor의 튜플로, 모양은(batch_size, num_heads, sequence_length, sequence_length)입니다.decoder의 cross-attention 레이어에서 attention softmax를 적용한 후, cross-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention 가중치입니다.
encoder_last_hidden_state (
torch.FloatTensor, shape(batch_size, sequence_length, hidden_size), 선택 사항) — 모델 인코더의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.encoder_hidden_states (
tuple(torch.FloatTensor), 선택,output_hidden_states=True가 전달되었거나config.output_hidden_states=True인 경우 반환됨) —torch.FloatTensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은(batch_size, sequence_length, hidden_size)입니다.각 레이어 출력의 인코더 hidden-states와 선택적인 초기 임베딩 출력.
encoder_attentions (
tuple(torch.FloatTensor), 선택,output_attentions=True가 전달되었거나config.output_attentions=True인 경우 반환됨) —torch.FloatTensor의 튜플(각 레이어마다 하나)로, 모양은(batch_size, num_heads, sequence_length, sequence_length)입니다.self-attention 헤드에서 가중 평균을 계산하는 데 사용되는, attention softmax 이후의 인코더 attention 가중치입니다.
T5Gemma2ForConditionalGeneration
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.FloatTensor] = Noneattention_mask: typing.Optional[torch.FloatTensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonedecoder_input_ids: typing.Optional[torch.LongTensor] = Nonedecoder_attention_mask: typing.Optional[torch.BoolTensor] = Nonedecoder_position_ids: typing.Optional[torch.LongTensor] = Noneencoder_outputs: transformers.modeling_outputs.BaseModelOutput | None = Nonepast_key_values: transformers.cache_utils.EncoderDecoderCache | None = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonedecoder_inputs_embeds: typing.Optional[torch.FloatTensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Seq2SeqLMOutput or tuple(torch.FloatTensor)
매개변수
- input_ids (
torch.LongTensor형상이(batch_size, sequence_length), 선택 사항) — 어휘(input vocabulary)에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.
- pixel_values (
torch.FloatTensor, shape(batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 Gemma3ImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 Gemma3ImageProcessor.call()를 참조하세요 (Gemma3Processor는 이미지 처리에 Gemma3ImageProcessor를 사용합니다). - attention_mask (
torch.FloatTensorshape(batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요?[0, 1]:- 마스크되지 않은 토큰에 대해 1
- 마스크된 토큰에 대해 0
- position_ids (
torch.LongTensor의 shape(batch_size, sequence_length), , 선택 사항) — 위치 임베딩에서 각 입력 시퀀스 토큰의 위치 인덱스. 범위[0, config.n_positions - 1]. - decoder_input_ids (
torch.LongTensor형상(batch_size, target_sequence_length), 선택 사항) — 어휘에서 디코더 입력 시퀀스 토큰의 인덱스입니다. AutoTokenizer를 사용하여 인덱스를 가져올 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()을 참조하세요. 디코더 입력 ID란 무엇인가요?AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.
- decoder_attention_mask (
torch.BoolTensor, shape(batch_size, target_sequence_length), 선택) — 특정 토큰 인덱스에 대한 attention을 수행하지 않도록 하는 mask입니다. 기본적으로 causal mask를 사용하여 모델이 미래를 예측할 때 이전 입력만 참조할 수 있도록 합니다. - decoder_position_ids (
torch.LongTensor, shape(batch_size, decoder_sequence_length), 선택 사항) — decoder 입력 시퀀스의 각 토큰이 position embeddings에서 차지하는 위치 인덱스입니다.[0, config.decoder.n_positions - 1]범위에서 선택됩니다. position ID란 무엇인가요? - encoder_outputs (
~modeling_outputs.BaseModelOutput, 선택 사항) — (last_hidden_state, 선택 사항:hidden_states, 선택 사항:attentions)의 Tuplelast_hidden_state의 shape은(batch_size, sequence_length, hidden_size), 선택 사항)이며, 인코더의 마지막 레이어 출력에서 생성된 hidden-states의 시퀀스입니다. 디코더의 cross-attention에 사용됩니다. - past_key_values (
~cache_utils.EncoderDecoderCache, 선택 사항) — 순차적 디코딩을 가속화할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록과 크로스 어텐션 블록의 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.FloatTensor, shape(batch_size, sequence_length, hidden_size), 선택) —input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델의 내부 임베딩 조회 행렬보다input_ids인덱스를 관련 벡터로 변환하는 방식에 대한 더 세밀한 제어가 필요한 경우 유용합니다. - decoder_inputs_embeds (
torch.FloatTensor형상이(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_idsdocstring 참조). 인덱스가-100으로 설정된 토큰은 무시(마스크)되며, 손실은[0, ..., config.vocab_size]범위의 라벨을 가진 토큰에 대해서만 계산됩니다. - use_cache (
bool, 선택 사항) —True로 설정하면past_key_values키 값 상태가 반환되며, 디코딩 속도를 높이는 데 사용할 수 있습니다(past_key_values참조). - logits_to_keep (
Union[int, torch.Tensor], 선택 사항, 기본값0) —int인 경우, 마지막logits_to_keep토큰에 대한 logits를 계산합니다.0인 경우, 모든input_ids에 대한 logits를 계산합니다(특수한 경우). 생성에는 마지막 토큰의 logits만 필요하며, 해당 토큰에 대해서만 계산하면 메모리를 절약할 수 있습니다. 이는 긴 시퀀스나 큰 어휘 크기의 경우 상당한 이점을 제공합니다.torch.Tensor인 경우, 시퀀스 길이 차원에서 유지할 인덱스에 해당하는 1차원 텐서여야 합니다. 이는 패킹된 텐서 형식(배치와 시퀀스 길이를 단일 차원으로 사용하는 경우)을 사용할 때 유용합니다.
반환값
Seq2SeqLMOutput 또는 tuple(torch.FloatTensor)
torch.FloatTensor의 튜플 또는 Seq2SeqLMOutput입니다. return_dict=False가 전달되었거나 config.return_dict=False인 경우에도 동일합니다. 구성(T5Gemma2Config)과 입력에 따라 다양한 요소를 포함합니다.
T5Gemma2ForConditionalGeneration의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.
이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신
Module인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.
loss (
torch.FloatTensor, shape(1,), 선택 사항,labels가 제공될 때 반환됨) — 언어 모델링 손실.logits (
torch.FloatTensor, 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.FloatTensor), 선택,output_hidden_states=True가 전달되었거나config.output_hidden_states=True인 경우 반환됨) —torch.FloatTensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 형태는(batch_size, sequence_length, hidden_size)입니다.각 레이어의 출력에서 디코더의 Hidden-states와 초기 임베딩 출력을 더한 값.
decoder_attentions (
tuple(torch.FloatTensor), 선택 사항,output_attentions=True가 전달되었거나config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된torch.FloatTensor의 튜플로, 모양은(batch_size, num_heads, sequence_length, sequence_length)입니다.self-attention 헤드에서 가중 평균을 계산하는 데 사용되는, attention softmax 이후의 decoder의 attention 가중치입니다.
cross_attentions (
tuple(torch.FloatTensor), 선택 사항,output_attentions=True가 전달되었거나config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된torch.FloatTensor의 튜플로, 모양은(batch_size, num_heads, sequence_length, sequence_length)입니다.decoder의 cross-attention 레이어에서 attention softmax를 적용한 후, cross-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention 가중치입니다.
encoder_last_hidden_state (
torch.FloatTensor, shape(batch_size, sequence_length, hidden_size), 선택 사항) — 모델 인코더의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.encoder_hidden_states (
tuple(torch.FloatTensor), 선택,output_hidden_states=True가 전달되었거나config.output_hidden_states=True인 경우 반환됨) —torch.FloatTensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은(batch_size, sequence_length, hidden_size)입니다.각 레이어의 출력에서 인코더의 Hidden-states와 초기 임베딩 출력을 더한 값.
encoder_attentions (
tuple(torch.FloatTensor), 선택,output_attentions=True가 전달되었거나config.output_attentions=True인 경우 반환됨) —torch.FloatTensor의 튜플(각 레이어마다 하나)로, 모양은(batch_size, num_heads, sequence_length, sequence_length)입니다.self-attention 헤드에서 가중 평균을 계산하는 데 사용되는, attention softmax 이후의 인코더 attention 가중치입니다.
예:
>>> from PIL import Image
>>> from transformers import AutoProcessor, T5Gemma2ForConditionalGeneration
>>> model = T5Gemma2ForConditionalGeneration.from_pretrained("google/t5gemma-2-270m-270m")
>>> processor = AutoProcessor.from_pretrained("google/t5gemma-2-270m-270m")
>>> messages = [
... {
... "role": "user", "content": [
... {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
... {"type": "text", "text": "Where is the cat standing?"},
... ]
... },
... ]
>>> inputs = processor.apply_chat_template(
... messages,
... tokenize=True,
... return_dict=True,
... return_tensors="pt",
... add_generation_prompt=True
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]get_image_features
< source >( pixel_values: Tensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.FloatTensor)
매개변수
- pixel_values (
torch.Tensor, shape(batch_size, num_channels, image_size, image_size)) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 Gemma3ImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 Gemma3ImageProcessor.call()를 참조하세요 (Gemma3Processor는 이미지 처리에 Gemma3ImageProcessor를 사용합니다).
반환값
BaseModelOutputWithPooling 또는 tuple(torch.FloatTensor)
torch.FloatTensor의 튜플 또는 BaseModelOutputWithPooling입니다. return_dict=False가 전달되었거나 config.return_dict=False인 경우, 구성(T5Gemma2Config)과 입력에 따라 다양한 요소를 포함합니다.
last_hidden_state (
torch.FloatTensor, shape(batch_size, sequence_length, hidden_size)) — 모델의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.pooler_output (
torch.FloatTensor, shape(batch_size, hidden_size)) — 시퀀스의 첫 번째 토큰(분류 토큰)의 마지막 레이어 hidden-state로, 보조 사전학습 작업을 위해 사용되는 레이어들을 통해 추가 처리된 값입니다. 예를 들어 BERT 계열 모델의 경우, 선형 레이어와 tanh 활성화 함수를 통해 처리된 분류 토큰을 반환합니다. 선형 레이어의 가중치는 사전학습 단계에서 다음 문장 예측(분류) 목적 함수를 통해 학습됩니다.hidden_states (
tuple(torch.FloatTensor), 선택 사항,output_hidden_states=True가 전달되었거나config.output_hidden_states=True인 경우 반환됨) —torch.FloatTensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은(batch_size, sequence_length, hidden_size)입니다.각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.
attentions (
tuple(torch.FloatTensor), 선택 사항,output_attentions=True가 전달되었거나config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된torch.FloatTensor의 튜플로, 형태는(batch_size, num_heads, sequence_length, sequence_length)입니다.self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치.
예:
>>> from PIL import Image
>>> from transformers import AutoProcessor, T5Gemma2ForConditionalGeneration
>>> model = T5Gemma2ForConditionalGeneration.from_pretrained("google/t5gemma-2-270m-270m")
>>> processor = AutoProcessor.from_pretrained("google/t5gemma-2-270m-270m")
>>> messages = [
... {
... "role": "user", "content": [
... {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
... {"type": "text", "text": "Where is the cat standing?"},
... ]
... },
... ]
>>> inputs = processor.apply_chat_template(
... messages,
... tokenize=True,
... return_dict=True,
... return_tensors="pt",
... add_generation_prompt=True
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]T5Gemma2ForSequenceClassification
클래스 transformers.T5Gemma2ForSequenceClassification
< source >( config: T5Gemma2Config )
매개변수
- config (T5Gemma2Config) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.
GLUE 작업과 같은 시퀀스 분류/회귀 작업을 위해 상단에 시퀀스 분류/회귀 헤드가 있는 T5Gemma2 모델.
이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.
이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.FloatTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonedecoder_input_ids: typing.Optional[torch.LongTensor] = Nonedecoder_attention_mask: typing.Optional[torch.Tensor] = Nonedecoder_position_ids: typing.Optional[torch.LongTensor] = Noneencoder_outputs: transformers.modeling_outputs.BaseModelOutput | None = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonedecoder_inputs_embeds: typing.Optional[torch.FloatTensor] = Nonelabels: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → SequenceClassifierOutput or tuple(torch.FloatTensor)
매개변수
- input_ids (
torch.LongTensor형상이(batch_size, sequence_length), 선택 사항) — 어휘(input vocabulary)에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.
- pixel_values (
torch.FloatTensor, shape(batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 Gemma3ImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 Gemma3ImageProcessor.call()를 참조하세요 (Gemma3Processor는 이미지 처리에 Gemma3ImageProcessor를 사용합니다). - attention_mask (
torch.Tensor형상이(batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요?[0, 1]:- 마스크되지 않은 토큰에 대해 1
- 마스크된 토큰에 대해 0
- position_ids (
torch.LongTensor의 shape(batch_size, sequence_length), , 선택 사항) — 위치 임베딩에서 각 입력 시퀀스 토큰의 위치 인덱스. 범위[0, config.n_positions - 1]. - decoder_input_ids (
torch.LongTensor형상(batch_size, target_sequence_length), 선택 사항) — 어휘에서 디코더 입력 시퀀스 토큰의 인덱스입니다. AutoTokenizer를 사용하여 인덱스를 가져올 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()을 참조하세요. 디코더 입력 ID란 무엇인가요?AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.
- decoder_attention_mask (
torch.Tensor, shape(batch_size, target_sequence_length), 선택 사항) — 특정 토큰 인덱스에 대한 attention을 수행하지 않도록 하는 mask입니다. 기본적으로 causal mask를 사용하여 모델이 미래를 예측할 때 이전 입력만 참조할 수 있도록 합니다. - decoder_position_ids (
torch.LongTensor, shape(batch_size, decoder_sequence_length), 선택 사항) — decoder 입력 시퀀스의 각 토큰이 position embeddings에서 차지하는 위치 인덱스입니다.[0, config.decoder.n_positions - 1]범위에서 선택됩니다. position ID란 무엇인가요? - encoder_outputs (
~modeling_outputs.BaseModelOutput, 선택 사항) — (last_hidden_state, 선택 사항:hidden_states, 선택 사항:attentions)의 Tuplelast_hidden_state의 shape은(batch_size, sequence_length, hidden_size), 선택 사항)이며, 인코더의 마지막 레이어 출력에서 생성된 hidden-states의 시퀀스입니다. 디코더의 cross-attention에 사용됩니다. - inputs_embeds (
torch.FloatTensor, shape(batch_size, sequence_length, hidden_size), 선택) —input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델의 내부 임베딩 조회 행렬보다input_ids인덱스를 관련 벡터로 변환하는 방식에 대한 더 세밀한 제어가 필요한 경우 유용합니다. - decoder_inputs_embeds (
torch.FloatTensor형상이(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,), 선택 사항) — 시퀀스 분류/회귀 손실을 계산하는 데 사용되는 라벨입니다. 인덱스는[0, ..., config.num_labels - 1]범위에 있어야 합니다.config.num_labels == 1인 경우 회귀 손실(Mean-Square loss)이 계산되고,config.num_labels > 1인 경우 분류 손실(Cross-Entropy)이 계산됩니다.
반환값
SequenceClassifierOutput 또는 tuple(torch.FloatTensor)
torch.FloatTensor의 튜플 또는 SequenceClassifierOutput입니다. return_dict=False가 전달되었거나 config.return_dict=False인 경우, T5Gemma2Config 설정과 입력에 따라 다양한 요소를 포함합니다.
T5Gemma2ForSequenceClassification의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.
이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신
Module인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.
loss (
torch.FloatTensor, shape(1,), 선택 사항,labels가 제공될 때 반환됨) — 분류(또는 config.num_labels==1인 경우 회귀) 손실.logits (
torch.FloatTensor, shape(batch_size, config.num_labels)) — SoftMax 적용 전 분류(또는 config.num_labels==1인 경우 회귀) 점수.hidden_states (
tuple(torch.FloatTensor), 선택 사항,output_hidden_states=True가 전달되었거나config.output_hidden_states=True인 경우 반환됨) —torch.FloatTensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은(batch_size, sequence_length, hidden_size)입니다.각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.
attentions (
tuple(torch.FloatTensor), 선택 사항,output_attentions=True가 전달되었거나config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된torch.FloatTensor의 튜플로, 형태는(batch_size, num_heads, sequence_length, sequence_length)입니다.self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치.
단일 레이블 분류의 예시:
>>> import torch
>>> from transformers import AutoTokenizer, T5Gemma2ForSequenceClassification
>>> tokenizer = AutoTokenizer.from_pretrained("google/t5gemma-2-270m-270m")
>>> model = T5Gemma2ForSequenceClassification.from_pretrained("google/t5gemma-2-270m-270m")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> with torch.no_grad():
... logits = model(**inputs).logits
>>> predicted_class_id = logits.argmax().item()
>>> model.config.id2label[predicted_class_id]
...
>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
>>> num_labels = len(model.config.id2label)
>>> model = T5Gemma2ForSequenceClassification.from_pretrained("google/t5gemma-2-270m-270m", num_labels=num_labels)
>>> labels = torch.tensor([1])
>>> loss = model(**inputs, labels=labels).loss
>>> round(loss.item(), 2)
...다중 레이블 분류의 예시:
>>> import torch
>>> from transformers import AutoTokenizer, T5Gemma2ForSequenceClassification
>>> tokenizer = AutoTokenizer.from_pretrained("google/t5gemma-2-270m-270m")
>>> model = T5Gemma2ForSequenceClassification.from_pretrained("google/t5gemma-2-270m-270m", problem_type="multi_label_classification")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> with torch.no_grad():
... logits = model(**inputs).logits
>>> predicted_class_ids = torch.arange(0, logits.shape[-1])[torch.sigmoid(logits).squeeze(dim=0) > 0.5]
>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
>>> num_labels = len(model.config.id2label)
>>> model = T5Gemma2ForSequenceClassification.from_pretrained(
... "google/t5gemma-2-270m-270m", num_labels=num_labels, problem_type="multi_label_classification"
... )
>>> labels = torch.sum(
... torch.nn.functional.one_hot(predicted_class_ids[None, :].clone(), num_classes=num_labels), dim=1
... ).to(torch.float)
>>> loss = model(**inputs, labels=labels).lossT5Gemma2ForTokenClassification
클래스 transformers.T5Gemma2ForTokenClassification
< source >( config: T5Gemma2Config )
매개변수
- config (T5Gemma2Config) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.
토큰 분류 헤드가 위에 있는 T5Gemma2 트랜스포머입니다(히든 스테이트 출력 위에 선형 레이어가 있는 형태). 예: Named-Entity-Recognition(NER) 작업.
이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.
이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.FloatTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonedecoder_input_ids: typing.Optional[torch.LongTensor] = Nonedecoder_attention_mask: typing.Optional[torch.Tensor] = Nonedecoder_position_ids: typing.Optional[torch.LongTensor] = Noneencoder_outputs: transformers.modeling_outputs.BaseModelOutput | None = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonedecoder_inputs_embeds: typing.Optional[torch.FloatTensor] = Nonelabels: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → TokenClassifierOutput or tuple(torch.FloatTensor)
매개변수
- input_ids (
torch.LongTensor형상이(batch_size, sequence_length), 선택 사항) — 어휘(input vocabulary)에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.
- pixel_values (
torch.FloatTensor, shape(batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 Gemma3ImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 Gemma3ImageProcessor.call()를 참조하세요 (Gemma3Processor는 이미지 처리에 Gemma3ImageProcessor를 사용합니다). - attention_mask (
torch.Tensor형상이(batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요?[0, 1]:- 마스크되지 않은 토큰에 대해 1
- 마스크된 토큰에 대해 0
- position_ids (
torch.LongTensor의 shape(batch_size, sequence_length), , 선택 사항) — 위치 임베딩에서 각 입력 시퀀스 토큰의 위치 인덱스. 범위[0, config.n_positions - 1]. - decoder_input_ids (
torch.LongTensor형상(batch_size, target_sequence_length), 선택 사항) — 어휘에서 디코더 입력 시퀀스 토큰의 인덱스입니다. AutoTokenizer를 사용하여 인덱스를 가져올 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()을 참조하세요. 디코더 입력 ID란 무엇인가요?AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.
- decoder_attention_mask (
torch.Tensor, shape(batch_size, target_sequence_length), 선택 사항) — 특정 토큰 인덱스에 대한 attention을 수행하지 않도록 하는 mask입니다. 기본적으로 causal mask를 사용하여 모델이 미래를 예측할 때 이전 입력만 참조할 수 있도록 합니다. - decoder_position_ids (
torch.LongTensor, shape(batch_size, decoder_sequence_length), 선택 사항) — decoder 입력 시퀀스의 각 토큰이 position embeddings에서 차지하는 위치 인덱스입니다.[0, config.decoder.n_positions - 1]범위에서 선택됩니다. position ID란 무엇인가요? - encoder_outputs (
~modeling_outputs.BaseModelOutput, 선택 사항) — (last_hidden_state, 선택 사항:hidden_states, 선택 사항:attentions)의 Tuplelast_hidden_state의 shape은(batch_size, sequence_length, hidden_size), 선택 사항)이며, 인코더의 마지막 레이어 출력에서 생성된 hidden-states의 시퀀스입니다. 디코더의 cross-attention에 사용됩니다. - inputs_embeds (
torch.FloatTensor, shape(batch_size, sequence_length, hidden_size), 선택) —input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델의 내부 임베딩 조회 행렬보다input_ids인덱스를 관련 벡터로 변환하는 방식에 대한 더 세밀한 제어가 필요한 경우 유용합니다. - decoder_inputs_embeds (
torch.FloatTensor형상이(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,), 선택 사항) — 시퀀스 분류/회귀 손실을 계산하는 데 사용되는 라벨입니다. 인덱스는[0, ..., config.num_labels - 1]범위에 있어야 합니다.config.num_labels == 1인 경우 회귀 손실(Mean-Square loss)이 계산되고,config.num_labels > 1인 경우 분류 손실(Cross-Entropy)이 계산됩니다.
반환값
TokenClassifierOutput 또는 tuple(torch.FloatTensor)
torch.FloatTensor의 튜플 또는 TokenClassifierOutput입니다. return_dict=False가 전달되었거나 config.return_dict=False인 경우, 구성(T5Gemma2Config)과 입력에 따라 다양한 요소를 포함합니다.
T5Gemma2ForTokenClassification의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.
이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신
Module인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.
loss (
torch.FloatTensor, shape(1,), 선택 사항,labels가 제공될 때 반환됨) — 분류 손실.logits (
torch.FloatTensor, shape(batch_size, sequence_length, config.num_labels)) — SoftMax 적용 전 분류 점수.hidden_states (
tuple(torch.FloatTensor), 선택 사항,output_hidden_states=True가 전달되었거나config.output_hidden_states=True인 경우 반환됨) —torch.FloatTensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은(batch_size, sequence_length, hidden_size)입니다.각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.
attentions (
tuple(torch.FloatTensor), 선택 사항,output_attentions=True가 전달되었거나config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된torch.FloatTensor의 튜플로, 형태는(batch_size, num_heads, sequence_length, sequence_length)입니다.self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치.
예:
>>> from transformers import AutoTokenizer, T5Gemma2ForTokenClassification
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("google/t5gemma-2-270m-270m")
>>> model = T5Gemma2ForTokenClassification.from_pretrained("google/t5gemma-2-270m-270m")
>>> inputs = tokenizer(
... "HuggingFace is a company based in Paris and New York", add_special_tokens=False, return_tensors="pt"
... )
>>> with torch.no_grad():
... logits = model(**inputs).logits
>>> predicted_token_class_ids = logits.argmax(-1)
>>> # Note that tokens are classified rather then input words which means that
>>> # there might be more predicted token classes than words.
>>> # Multiple token classes might account for the same word
>>> predicted_tokens_classes = [model.config.id2label[t.item()] for t in predicted_token_class_ids[0]]
>>> predicted_tokens_classes
...
>>> labels = predicted_token_class_ids
>>> loss = model(**inputs, labels=labels).loss
>>> round(loss.item(), 2)
...