Transformers documentation

Inkling 2 Small

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

and get access to the augmented documentation experience

to get started

이 모델은 2026-11-11에 Hugging Face Transformers에 기여되었습니다.

Inkling 2 Small

Inkling 2 Small은 Thinking Machines Lab에서 개발한 멀티모달 모델로, 텍스트와 이미지 입력을 받아 텍스트 출력을 생성합니다. 영어를 비롯한 다양한 언어 및 여러 코딩 언어 환경에서 사용하도록 설계되었습니다. 학습된 상대적 어텐션, 짧은 인과적 컨볼루션, mixture-of-experts 레이어를 갖춘 Inkling의 디코더를 유지하면서, 블록 어텐션 잔차, 학습된 sink를 가진 게이트드 어텐션, 동적 key/value 컨볼루션을 추가했습니다. 언어 백본은 48개의 mixture-of-experts 디코더 레이어로 구성되며, 각 레이어는 토큰을 384개 전문가 중 8개로 라우팅합니다. 이 모델의 총 파라미터 수는 594B, 활성 파라미터 수는 17B입니다. 이미지는 Perception Encoder 기반의 비전 트랜스포머로 인코딩된 후, 40x40 픽셀 패치당 하나의 임베딩으로 언어 모델 임베딩 공간에 투영됩니다.

모델은 두 개의 체크포인트와 함께 공개됩니다:

두 체크포인트 모두 양자화 레이어를 포함합니다. Inkling-2-Small에는 NVFP4와 MXFP8 양자화 디코더 레이어가 모두 포함되어 있습니다. Inkling-2-Small-MXFP8에는 MXFP8 양자화 레이어만 포함되어 있습니다. 현재 Inkling-2-Small-MXFP8 체크포인트만 지원됩니다.

리소스

Pipeline
AutoModel
import torch

from transformers import pipeline

pipe = pipeline(
    "image-text-to-text", model="thinkingmachines/Inkling-2-Small-MXFP8", dtype=torch.bfloat16, device_map="auto"
)

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image",
                "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg",
            },
            {"type": "text", "text": "What animal is in this image, and where is it?"},
        ],
    },
]

output = pipe(messages, max_new_tokens=1024, return_full_text=False, skip_special_tokens=False)
print(output[0]["generated_text"])
# <|message_model|><|content_thinking|>The user is asking to identify the animal and location in the image. Need answer based on visible content. The animal looks like a Pallas's cat (Otocolobus manul), also called manul:
# ...
# <|end_message|><|message_model|><|content_text|>The animal is a **Pallas’s cat** (also called a **manul**). It’s walking through **snow** in front of birch logs, likely in a **zoo or enclosed habitat**. The exact geographic location can’t be determined from the image alone; in the wild they’re native to parts of **Central Asia**.<|end_message|><|content_model_end_sampling|>

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

  • 각 레이어마다 상대 위치 편향과 sink가 추가되므로 Attention은 eager 모드에서만 실행됩니다.

Inkling2Config

클래스 transformers.Inkling2Config

< >

( 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.models.inkling2.configuration_inkling2.Inkling2TextConfig | dict | None = Nonevision_config: transformers.models.inkling2.configuration_inkling2.Inkling2VisionConfig | dict | None = Noneimage_token_id: int = 200054 )

매개변수

  • text_config (Union[~models.inkling2.configuration_inkling2.Inkling2TextConfig, dict], 선택 사항) — 텍스트 백본의 config 객체 또는 사전입니다.
  • vision_config (Union[~models.inkling2.configuration_inkling2.Inkling2VisionConfig, dict], 선택) — 비전 백본의 config 객체 또는 사전입니다.
  • image_token_id (int, 선택 사항, 기본값 200054) — 이미지 플레이스홀더의 토큰 인덱스입니다. 각 플레이스홀더는 하나의 이미지 특징으로 대체됩니다.

이것은 Inkling2Model의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 Inkling2 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 인스턴스화하면 thinkingmachines/Inkling-2-Small-MXFP8의 구성과 유사한 구성이 생성됩니다.

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

Inkling2TextConfig

클래스 transformers.Inkling2TextConfig

< >

( 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 = 201024unpadded_vocab_size: int = 200058hidden_size: int = 4608num_hidden_layers: int = 48num_attention_heads: int = 48num_key_value_heads: int = 8head_dim: int = 128swa_num_attention_heads: int = 48swa_num_key_value_heads: int = 8swa_head_dim: int = 128sliding_window_size: int = 1024d_rel: int = 16rel_extent: int = 1024log_scaling_n_floor: int = 128000log_scaling_alpha: float = 0.1layer_types: list[str] | None = Nonemax_position_embeddings: int = 1048576rms_norm_eps: float = 1e-06conv_kernel_size: int = 4hidden_act: str = 'silu'moe_intermediate_size: int = 2304n_routed_experts: int = 384num_experts_per_tok: int = 8route_scale: float = 8.0attention_dropout: float = 0.0initializer_range: float = 0.02pad_token_id: int | None = Nonebos_token_id: int | None = Noneeos_token_id: int | None = 200006qk_l2_clip_threshold: float = 22.627416997969522rel_l2_clip_threshold: float = 8.0n_layers_per_attn_res_block: int = 6mlp_gate_softcap: float = 4.0mlp_up_softcap: float = 25.0final_logit_softcapping: float = 30.0scoring_func: str = 'sigmoid'use_cache: bool = True )

매개변수

  • vocab_size (int, 선택 사항, 기본값 201024) — 모델의 어휘 크기입니다. input_ids로 표현할 수 있는 서로 다른 토큰의 수를 정의합니다.
  • unpadded_vocab_size (int, 선택 사항, 기본값 200058) — 실제 토큰을 포함하는 unembedding 행렬의 행 수입니다. 이 범위를 초과하는 logits는 제거됩니다.
  • hidden_size (int, 선택 사항, 기본값 4608) — 숨겨진 표현의 차원입니다.
  • num_hidden_layers (int, 선택 사항, 기본값 48) — Transformer decoder의 숨겨진 레이어 수입니다.
  • num_attention_heads (int, 선택 사항, 기본값 48) — Transformer decoder의 각 attention layer에 사용할 attention head의 수입니다.
  • num_key_value_heads (int, 선택 사항, 기본값 8) — 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, 선택 사항, 기본값 128) — Attention head의 차원입니다. None인 경우 hidden_size // num_attention_heads 값이 기본값으로 사용됩니다.
  • swa_num_attention_heads (int, 선택 사항, 기본값 48) — 슬라이딩 윈도우 레이어의 attention head 수.
  • swa_num_key_value_heads (int, 선택 사항, 기본값 8) — 슬라이딩 윈도우 레이어의 key/value 헤드 수.
  • swa_head_dim (int, 선택 사항, 기본값 128) — 슬라이딩 윈도우 레이어에서 쿼리 및 키 헤드의 차원입니다.
  • sliding_window_size (int, 선택 사항, 기본값 1024) — layer_types 항목이 "hybrid_sliding"인 레이어에서 사용되는 슬라이딩 어텐션 윈도우의 크기입니다.
  • d_rel (int, 선택 사항, 기본값 16) — 상대 위치 편향에 혼합되는 상대 상태의 헤드별 차원입니다.
  • rel_extent (int, 선택 사항, 기본값 1024) — 풀 어텐션 레이어에서 상대 위치 편향이 적용되는 토큰 수 기준의 후방 거리입니다.
  • log_scaling_n_floor (int, 선택 사항, 기본값 128000) — 풀 어텐션 레이어에서 쿼리와 상대 상태가 로그적으로 스케일업되는 시작 위치입니다.
  • log_scaling_alpha (float, 선택 사항, 기본값 0.1) — log_scaling_n_floor에 의해 제어되는 로그 스케일링의 강도.
  • layer_types (list[str], 선택 사항) — 각 레이어 인덱스를 해당 레이어 유형에 명시적으로 매핑하는 목록입니다. 제공되지 않으면 config 값에 기반하여 자동으로 생성됩니다.
  • max_position_embeddings (int, 선택 사항, 기본값 1048576) — 이 모델이 사용될 수 있는 최대 시퀀스 길이입니다.
  • rms_norm_eps (float, 선택 사항, 기본값 1e-06) — rms 정규화 레이어에서 사용되는 epsilon 값입니다.
  • conv_kernel_size (int, 선택 사항, 기본값 4) — 합성곱 커널의 크기입니다.
  • hidden_act (str, 선택 사항, 기본값 silu) — 디코더의 비선형 활성화 함수(함수 또는 문자열)입니다. 예를 들어, "gelu", "relu", "silu" 등이 있습니다.
  • moe_intermediate_size (int, 선택 사항, 기본값 2304) — 라우팅된 전문가 MLP의 중간 크기입니다.
  • n_routed_experts (int, 선택 사항, 기본값 384) — 라우팅된 전문가의 수입니다.
  • num_experts_per_tok (int, 선택 사항, 기본값 8) — 각 토큰을 라우팅할 전문가의 수입니다. 이는 토큰 선택 라우팅의 top-k 값입니다.
  • route_scale (float, 선택 사항, 기본값 8.0) — 라우팅된 전문가에 대한 스케일링 계수입니다.
  • attention_dropout (float, 선택 사항, 기본값 0.0) — Attention 확률에 적용할 dropout 비율입니다.
  • initializer_range (float, 선택 사항, 기본값 0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.
  • pad_token_id (int, 선택 사항) — 어휘에서 패딩에 사용되는 토큰 ID입니다.
  • bos_token_id (int, 선택 사항) — 어휘에서 스트림 시작에 사용되는 토큰 ID입니다.
  • eos_token_id (int, 선택 사항, 기본값 200006) — 어휘에서 스트림 종료에 사용되는 토큰 ID입니다.
  • qk_l2_clip_threshold (float, 선택 사항, 기본값 22.627416997969522) — 각 쿼리 및 키 헤드 벡터의 최대 L2 노름입니다. 이 노름보다 긴 벡터는 해당 노름으로 축소됩니다.
  • rel_l2_clip_threshold (float, 선택 사항, 기본값 8.0) — 각 상대 상태 헤드 벡터의 최대 L2 노름.
  • n_layers_per_attn_res_block (int, 선택 사항, 기본값 6) — 블록이 attention residuals의 소스가 되기 전에 하나의 블록으로 합산되는 decoder 레이어의 수입니다.
  • mlp_gate_softcap (float, 선택 사항, 기본값 4.0) — 전문가들의 게이트 투영 선형 부분에 적용되는 소프트캡입니다.
  • mlp_up_softcap (float, 선택 사항, 기본값 25.0) — 전문가들의 업 프로젝션에 적용되는 소프트캡입니다.
  • final_logit_softcapping (float, 선택 사항, 기본값 30.0) — 출력 logits에 적용되는 softcap입니다.
  • scoring_func (str, 선택 사항, 기본값 "sigmoid") — 라우터 로짓을 전문가 점수로 변환하는 활성화 함수.
  • use_cache (bool, 선택 사항, 기본값 True) — 모델이 마지막 key/values attention을 반환할지 여부입니다(모든 모델에서 사용되지 않음). config.is_decoder=True인 경우 또는 모델이 decoder-only 생성 모델인 경우에만 관련이 있습니다.

이것은 Inkling2Model의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 Inkling2 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 인스턴스화하면 thinkingmachines/Inkling-2-Small-MXFP8의 구성과 유사한 구성이 생성됩니다.

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

Inkling2VisionConfig

클래스 transformers.Inkling2VisionConfig

< >

( 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 = Nonehidden_size: int = 1024intermediate_size: int | None = Nonenum_hidden_layers: int = 23num_attention_heads: int = 16num_channels: int = 3patch_size: int = 20hidden_act: str = 'gelu'layer_norm_eps: float = 1e-05attention_dropout: float | int = 0.0mlp_ratio: float = 4.0layer_scale_init_value: float = 0.1rope_parameters: dict | None = Nonespatial_merge_size: int = 2posemb_grid_size: int = 32projection_hidden_dim: int = 4096projector_bias: bool = Falsetext_hidden_size: int = 4608initializer_range: float = 0.02 )

매개변수

  • hidden_size (int, 선택 사항, 기본값 1024) — 숨겨진 표현의 차원입니다.
  • intermediate_size (int, 선택 사항) — MLP 표현의 차원.
  • num_hidden_layers (int, 선택 사항, 기본값 23) — Transformer 디코더의 숨겨진 레이어 수.
  • num_attention_heads (int, 선택 사항, 기본값 16) — Transformer decoder의 각 attention layer에 사용할 attention head의 수입니다.
  • num_channels (int, 선택 사항, 기본값 3) — 입력 채널의 수입니다.
  • patch_size (int, 선택 사항, 기본값 20) — 각 패치의 크기(해상도)입니다.
  • hidden_act (str, 선택 사항, 기본값 gelu) — 디코더에서 사용되는 비선형 활성화 함수(함수 또는 문자열)입니다. 예를 들어, "gelu", "relu", "silu" 등이 있습니다.
  • layer_norm_eps (float, 선택 사항, 기본값 1e-05) — 레이어 정규화 레이어에서 사용되는 epsilon 값입니다.
  • attention_dropout (Union[float, int], 선택 사항, 기본값 0.0) — Attention 확률에 적용할 dropout 비율입니다.
  • mlp_ratio (float, 선택 사항, 기본값 4.0) — 임베딩 차원에 대한 MLP 숨겨진 차원의 비율입니다.
  • layer_scale_init_value (float, 선택 사항, 기본값 0.1) — self-attention 레이어에서 사용할 스케일 값입니다. base 모델에는 0.1, large 모델에는 1e-6을 사용합니다. layer scale을 비활성화하려면 0으로 설정합니다.
  • rope_parameters (dict, 선택) — RoPE 임베딩의 구성 매개변수를 포함하는 사전입니다. 사전에는 rope_theta 값이 포함되어야 하며, 더 긴 max_position_embeddings로 RoPE를 사용하려는 경우 스케일링에 사용되는 매개변수를 선택적으로 포함할 수 있습니다.
  • spatial_merge_size (int, 선택 사항, 기본값 2) — 하나의 language model token으로 연결되는 patch feature 정사각형의 한 변 길이(네이티브 patch 단위).
  • posemb_grid_size (int, 선택 사항, 기본값 32) — 학습된 위치 임베딩 그리드의 한 변 길이로, 각 이미지의 네이티브 패치 그리드에 보간됩니다.
  • projection_hidden_dim (int, 선택 사항, 기본값 4096) — 병합된 패치 특징을 언어 모델로 투영하는 MLP의 숨겨진 크기입니다.
  • projector_bias (bool, 선택 사항, 기본값 False) — 투사 MLP가 바이어스를 사용하는지 여부.
  • text_hidden_size (int, 선택 사항, 기본값 4608) — 이미지 기능이 투영되는 언어 모델의 숨겨진 크기(hidden size)입니다.
  • initializer_range (float, 선택 사항, 기본값 0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.

이것은 Inkling2Model의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 Inkling2 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 인스턴스화하면 thinkingmachines/Inkling-2-Small-MXFP8의 구성과 유사한 구성이 생성됩니다.

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

Inkling2PreTrainedModel

클래스 transformers.Inkling2PreTrainedModel

< >

( config: PreTrainedConfig*inputs**kwargs )

매개변수

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

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

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

forward

( *args**kwargs )

점으로 구분된 경로(예: torch.float32)에 대한 mock 값: 속성 접근 체인, 호출은 pass-through 데코레이터처럼 동작하며, repr은 해당 점으로 구분된 경로입니다. 이를 베이스 클래스로 사용하면 plain-type 베이스로 대체됩니다(PEP 560 __mro_entries__). 따라서 실제 서브클래스는 일반적인 메타클래스를 유지하고, inspect.signature는 mock의 __init__가 아닌 실제 __init__를 읽습니다.

Inkling2TextModel

클래스 transformers.Inkling2TextModel

< >

( config: Inkling2TextConfig )

매개변수

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

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

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

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

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → MoeModelOutputWithPast or tuple(torch.Tensor)

매개변수

  • input_ids (torch.LongTensor 형상이 (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

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

  • position_ids (torch.LongTensor 의 shape (batch_size, sequence_length), , 선택 사항) — 위치 임베딩에서 각 입력 시퀀스 토큰의 위치 인덱스. 범위 [0, config.n_positions - 1].

    포지션 ID란 무엇인가요?

  • cache (~cache_utils.Cache, 선택 사항) — 순차적 디코딩을 가속화할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록과 크로스 어텐션 블록의 key와 value)입니다. 이는 일반적으로 cache 디코딩의 이전 단계에서 모델이 반환한 use_cache=True 또는 config.use_cache=True.

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

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

    cache가 사용되는 경우, 이 모델에 과거 키 값 상태가 제공되지 않은 input_ids만, 즉 (batch_size, sequence_length) 모양의 모든 input_ids 대신 (batch_size, unprocessed_length) 모양의 처리되지 않은 input_ids를 입력해야 합니다.

  • inputs_embeds (torch.Tensor, shape (batch_size, sequence_length, hidden_size), 선택) — input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델 내부의 임베딩 조회 행렬보다 input_ids 인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다.
  • use_cache (bool, 선택 사항) — True로 설정하면 cache 키 값 상태가 반환되며, 디코딩 속도를 높이는 데 사용할 수 있습니다( cache 참조).

반환값

MoeModelOutputWithPast 또는 tuple(torch.Tensor)

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

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

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

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

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

    순차적 디코딩을 가속화하는 데 사용할 수 있는 사전 계산된 hidden-states(셀프-어텐션 블록의 key와 value, 그리고 config.is_encoder_decoder=True인 경우 크로스-어텐션 블록의 key와 value)를 포함합니다(사용 방법은 cache 입력을 참조).

  • 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와 선택적 초기 임베딩 출력을 포함합니다.

  • 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 가중치.

  • router_logits (tuple(torch.Tensor), 선택 사항, output_router_probs=True와 config.add_router_probs=True가 전달되었거나 config.output_router_probs=True인 경우 반환됨) — 각 레이어마다 하나씩, 모양이 (batch_size, sequence_length, num_experts)인 torch.Tensor의 튜플.

    MoE 라우터가 계산하는 softmax 적용 후의 원시 라우터 로짓(raw router logits)입니다. 이 값들은 Mixture of Experts 모델의 보조 손실(auxiliary loss)을 계산하는 데 사용됩니다.

Inkling2ForCausalLM

클래스 transformers.Inkling2ForCausalLM

< >

( config: Inkling2TextConfig )

매개변수

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

Inkling2 모델은 인과적 언어 모델링을 위한 것입니다.

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

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

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Inkling2CausalLMOutputWithPast or tuple(torch.Tensor)

매개변수

  • input_ids (torch.LongTensor 형상이 (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

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

  • position_ids (torch.LongTensor 의 shape (batch_size, sequence_length), , 선택 사항) — 위치 임베딩에서 각 입력 시퀀스 토큰의 위치 인덱스. 범위 [0, config.n_positions - 1].

    포지션 ID란 무엇인가요?

  • cache (~cache_utils.Cache, 선택 사항) — 순차적 디코딩을 가속화할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록과 크로스 어텐션 블록의 key와 value)입니다. 이는 일반적으로 cache 디코딩의 이전 단계에서 모델이 반환한 use_cache=True 또는 config.use_cache=True.

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

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

    cache가 사용되는 경우, 이 모델에 과거 키 값 상태가 제공되지 않은 input_ids만, 즉 (batch_size, sequence_length) 모양의 모든 input_ids 대신 (batch_size, unprocessed_length) 모양의 처리되지 않은 input_ids를 입력해야 합니다.

  • inputs_embeds (torch.Tensor, shape (batch_size, sequence_length, hidden_size), 선택) — input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델 내부의 임베딩 조회 행렬보다 input_ids 인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다.
  • labels (torch.LongTensor 형태가 (batch_size, sequence_length), 선택 사항) — causal language modeling loss를 계산하기 위한 라벨. 인덱스는 [-100, 0, ..., config.vocab_size] (참조 input_ids 문서 문자열). 인덱스가 -100 으로 설정된 토큰은 무시(마스크)되며, loss는 라벨이 [0, ..., config.vocab_size].

    레이블은 내부적으로 시프트되어 labels[..., 1:]가 logits[..., :-1, :]를 예측하는 데 사용됩니다. input_ids와 일치하는 시프트되지 않은 레이블을 전달하세요(즉, labels = input_ids). 전달하기 전에 레이블을 직접 시프트하지 마세요.

    레이블이 이미 시프트된 경우(예: 시퀀스 병렬성 사용 시), shift_labels 키워드 인수로 전달하면 그대로 사용됩니다. 손실이 계산되려면 labels도 여전히 전달되어야 합니다.

  • use_cache (bool, 선택 사항) — True로 설정하면 cache 키 값 상태가 반환되며, 디코딩 속도를 높이는 데 사용할 수 있습니다( cache 참조).
  • logits_to_keep (Union[int, torch.Tensor], 선택 사항, 기본값 0) — int인 경우, 마지막 logits_to_keep 토큰에 대한 logits를 계산합니다. 0인 경우, 모든 input_ids에 대한 logits를 계산합니다(특수한 경우). 생성에는 마지막 토큰의 logits만 필요하며, 해당 토큰에 대해서만 계산하면 메모리를 절약할 수 있습니다. 이는 긴 시퀀스나 큰 어휘 크기의 경우 상당한 이점을 제공합니다. torch.Tensor인 경우, 시퀀스 길이 차원에서 유지할 인덱스에 해당하는 1차원 텐서여야 합니다. 이는 패킹된 텐서 형식(배치와 시퀀스 길이를 단일 차원으로 사용하는 경우)을 사용할 때 유용합니다.

반환값

Inkling2CausalLMOutputWithPast 또는 tuple(torch.Tensor)

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

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

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

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

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

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

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

  • 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와 선택적 초기 임베딩 출력을 포함합니다.

  • 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 가중치.

  • image_hidden_states (torch.Tensor, 선택 사항) — 크기가 (batch_size, num_images, sequence_length, hidden_size)인 torch.Tensor입니다. 비전 인코더가 마지막 hidden state를 투사한 후 모델이 생성한 image_hidden_states입니다.

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

    Mixture of Experts 모델의 보조 손실을 계산하는 데 유용한 모델의 Router logits입니다.

예:

>>> import torch
>>> from transformers import AutoTokenizer, Inkling2ForCausalLM

>>> tokenizer = AutoTokenizer.from_pretrained("thinkingmachines/Inkling-2-Small-MXFP8")
>>> model = Inkling2ForCausalLM.from_pretrained(
...     "thinkingmachines/Inkling-2-Small-MXFP8", dtype=torch.bfloat16, device_map="auto"
... )

>>> messages = [{"role": "user", "content": "Explain in one sentence why the sky is usually blue."}]
>>> inputs = tokenizer.apply_chat_template(
...     messages,
...     tokenize=True,
...     add_generation_prompt=True,
...     return_dict=True,
...     return_tensors="pt",
... ).to(model.device)
>>> input_len = inputs["input_ids"].shape[-1]

>>> outputs = model.generate(**inputs, max_new_tokens=1024)
>>> print(tokenizer.decode(outputs[0][input_len:], skip_special_tokens=False))

Inkling2VisionModel

클래스 transformers.Inkling2VisionModel

< >

( config: Inkling2VisionConfig )

매개변수

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

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

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

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

forward

< >

( pixel_values: Tensorimage_grid_thw: Tensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

매개변수

  • pixel_values (torch.Tensor, shape (num_image_tokens, patch_size * spatial_merge_size, patch_size * spatial_merge_size, num_channels)) — [-1, 1] 범위의 이미지 패치입니다. 각 언어 모델 이미지 토큰당 하나씩, 이미지 내에서 라스터 순서대로 배치됩니다.
  • image_grid_thw (torch.Tensor, shape (num_images, 3)) — 각 이미지의 시간, 높이, 너비. 언어 모델의 이미지 토큰 단위로 계산됩니다.

반환값

BaseModelOutputWithPooling 또는 tuple(torch.Tensor)

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

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

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

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

  • pooler_output (torch.Tensor, shape (batch_size, hidden_size)) — 보조 사전 학습 작업을 위해 사용되는 레이어들을 통해 추가 처리된 시퀀스의 첫 번째 토큰(분류 토큰)의 마지막 레이어 hidden-state입니다. 예를 들어 BERT 계열 모델의 경우, 선형 레이어와 tanh 활성화 함수를 통해 처리된 후의 분류 토큰을 반환합니다. 선형 레이어의 가중치는 사전 학습 동안 다음 문장 예측(분류) 목적 함수를 통해 학습됩니다.

  • 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와 선택적 초기 임베딩 출력을 포함합니다.

  • 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 가중치.

Inkling2Model

클래스 transformers.Inkling2Model

< >

( config: Inkling2Config )

매개변수

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

언어 모델링 헤드가 없는 비전 백본과 언어 모델로 구성된 Base Inkling2 모델.

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

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

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Noneimage_grid_thw: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = Nonemm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Inkling2ModelOutputWithPast or tuple(torch.Tensor)

매개변수

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

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

    입력 ID란 무엇인가요?

  • pixel_values (torch.Tensor, shape (batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 image_processor_class를 사용하여 얻을 수 있습니다. 자세한 내용은 image_processor_class.__call__를 참조하세요 (processor_class는 이미지 처리에 image_processor_class를 사용합니다).
  • image_grid_thw (torch.LongTensor, shape (num_images, 3), 선택 사항) — 각 이미지의 시간, 높이, 너비입니다. 언어 모델의 이미지 토큰 단위로 계산됩니다.
  • 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].

    포지션 ID란 무엇인가요?

  • cache (~cache_utils.Cache, 선택 사항) — 순차적 디코딩을 가속화할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록과 크로스 어텐션 블록의 key와 value)입니다. 이는 일반적으로 cache 디코딩의 이전 단계에서 모델이 반환한 use_cache=True 또는 config.use_cache=True.

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

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

    cache가 사용되는 경우, 이 모델에 과거 키 값 상태가 제공되지 않은 input_ids만, 즉 (batch_size, sequence_length) 모양의 모든 input_ids 대신 (batch_size, unprocessed_length) 모양의 처리되지 않은 input_ids를 입력해야 합니다.

  • inputs_embeds (torch.Tensor, shape (batch_size, sequence_length, hidden_size), 선택) — input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델 내부의 임베딩 조회 행렬보다 input_ids 인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다.
  • use_cache (bool, 선택 사항) — True로 설정하면 cache 키 값 상태가 반환되며, 디코딩 속도를 높이는 데 사용할 수 있습니다( cache 참조).
  • mm_encoder_outputs (dict[str, ~modeling_outputs.BaseModelOutputWithPooling], 선택 사항) — 키가 지원되는 모달리티이고 값이 해당 모달리티의 인코딩된 출력인 딕셔너리입니다. 각 인코딩된 출력은 (pooler_output, 선택 사항: last_hidden_states, 선택 사항: hidden_states, 선택 사항: attentions) pooler_output의 형태가 (batch_size, sequence_length, hidden_size)인 선택 사항)으로 구성된 튜플이며, 인코더의 멀티모달 특징을 텍스트 임베딩에 병합한 시퀀스입니다.

반환값

Inkling2ModelOutputWithPast 또는 tuple(torch.Tensor)

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

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

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

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

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

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

    순차적 디코딩을 가속화하는 데 사용할 수 있는 사전 계산된 hidden-states(셀프-어텐션 블록의 key와 value, 그리고 config.is_encoder_decoder=True인 경우 크로스-어텐션 블록의 key와 value)를 포함합니다(사용 방법은 cache 입력을 참조).

  • 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와 선택적 초기 임베딩 출력을 포함합니다.

  • 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 가중치.

  • image_hidden_states (torch.Tensor, 선택 사항) — 크기가 (batch_size, num_images, sequence_length, hidden_size)인 torch.Tensor입니다. 비전 인코더가 생성한 모델의 image_hidden_states이며, 마지막 hidden state를 투영한 후의 값입니다.

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

    Mixture of Experts 모델의 보조 손실을 계산하는 데 유용한 모델의 Router logits입니다.

예:

>>> import torch
>>> from transformers import AutoProcessor, Inkling2Model

>>> processor = AutoProcessor.from_pretrained("thinkingmachines/Inkling-2-Small-MXFP8")
>>> model = Inkling2Model.from_pretrained(
...     "thinkingmachines/Inkling-2-Small-MXFP8", dtype=torch.bfloat16, device_map="auto"
... )

>>> messages = [
...     {
...         "role": "user",
...         "content": [
...             {
...                 "type": "image",
...                 "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg",
...             },
...             {"type": "text", "text": "What animal is in this image, and where is it?"},
...         ],
...     },
... ]

>>> inputs = processor.apply_chat_template(
...     messages,
...     tokenize=True,
...     add_generation_prompt=True,
...     return_dict=True,
...     return_tensors="pt",
... ).to(model.device)

>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state

Inkling2ForConditionalGeneration

클래스 transformers.Inkling2ForConditionalGeneration

< >

( config: Inkling2Config )

매개변수

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

언어 모델링 헤드가 없는 비전 백본과 언어 모델로 구성된 Base Inkling2 모델.

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

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

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Noneimage_grid_thw: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Inkling2CausalLMOutputWithPast or tuple(torch.Tensor)

매개변수

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

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

    입력 ID란 무엇인가요?

  • pixel_values (torch.Tensor, shape (batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 image_processor_class를 사용하여 얻을 수 있습니다. 자세한 내용은 image_processor_class.__call__를 참조하세요 (processor_class는 이미지 처리에 image_processor_class를 사용합니다).
  • image_grid_thw (torch.LongTensor, shape (num_images, 3), 선택 사항) — 각 이미지의 시간, 높이, 너비입니다. 언어 모델의 이미지 토큰 단위로 계산됩니다.
  • 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].

    포지션 ID란 무엇인가요?

  • cache (~cache_utils.Cache, 선택 사항) — 순차적 디코딩을 가속화할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록과 크로스 어텐션 블록의 key와 value)입니다. 이는 일반적으로 cache 디코딩의 이전 단계에서 모델이 반환한 use_cache=True 또는 config.use_cache=True.

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

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

    cache가 사용되는 경우, 이 모델에 과거 키 값 상태가 제공되지 않은 input_ids만, 즉 (batch_size, sequence_length) 모양의 모든 input_ids 대신 (batch_size, unprocessed_length) 모양의 처리되지 않은 input_ids를 입력해야 합니다.

  • inputs_embeds (torch.Tensor, shape (batch_size, sequence_length, hidden_size), 선택) — input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델 내부의 임베딩 조회 행렬보다 input_ids 인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다.
  • 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로 설정하면 cache 키 값 상태가 반환되며, 디코딩 속도를 높이는 데 사용할 수 있습니다( cache 참조).
  • logits_to_keep (Union[int, torch.Tensor], 선택 사항, 기본값 0) — int인 경우, 마지막 logits_to_keep 토큰에 대한 logits를 계산합니다. 0인 경우, 모든 input_ids에 대한 logits를 계산합니다(특수한 경우). 생성에는 마지막 토큰의 logits만 필요하며, 해당 토큰에 대해서만 계산하면 메모리를 절약할 수 있습니다. 이는 긴 시퀀스나 큰 어휘 크기의 경우 상당한 이점을 제공합니다. torch.Tensor인 경우, 시퀀스 길이 차원에서 유지할 인덱스에 해당하는 1차원 텐서여야 합니다. 이는 패킹된 텐서 형식(배치와 시퀀스 길이를 단일 차원으로 사용하는 경우)을 사용할 때 유용합니다.
  • mm_encoder_outputs (dict[str, ~modeling_outputs.BaseModelOutputWithPooling], 선택 사항) — 키가 지원되는 모달리티이고 값이 해당 모달리티의 인코딩된 출력인 딕셔너리입니다. 각 인코딩된 출력은 (pooler_output, 선택 사항: last_hidden_states, 선택 사항: hidden_states, 선택 사항: attentions) pooler_output의 형태가 (batch_size, sequence_length, hidden_size)인 선택 사항)으로 구성된 튜플이며, 인코더의 멀티모달 특징을 텍스트 임베딩에 병합한 시퀀스입니다.

반환값

Inkling2CausalLMOutputWithPast 또는 tuple(torch.Tensor)

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

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

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

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

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

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

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

  • 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와 선택적 초기 임베딩 출력을 포함합니다.

  • 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 가중치.

  • image_hidden_states (torch.Tensor, 선택 사항) — 크기가 (batch_size, num_images, sequence_length, hidden_size)인 torch.Tensor입니다. 비전 인코더가 마지막 hidden state를 투사한 후 모델이 생성한 image_hidden_states입니다.

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

    Mixture of Experts 모델의 보조 손실을 계산하는 데 유용한 모델의 Router logits입니다.

예:

>>> import torch
>>> from transformers import AutoProcessor, Inkling2ForConditionalGeneration

>>> processor = AutoProcessor.from_pretrained("thinkingmachines/Inkling-2-Small-MXFP8")
>>> model = Inkling2ForConditionalGeneration.from_pretrained(
...     "thinkingmachines/Inkling-2-Small-MXFP8", dtype=torch.bfloat16, device_map="auto"
... )

>>> messages = [
...     {
...         "role": "user",
...         "content": [
...             {
...                 "type": "image",
...                 "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg",
...             },
...             {"type": "text", "text": "What animal is in this image, and where is it?"},
...         ],
...     },
... ]

>>> inputs = processor.apply_chat_template(
...     messages,
...     tokenize=True,
...     add_generation_prompt=True,
...     return_dict=True,
...     return_tensors="pt",
... ).to(model.device)
>>> input_len = inputs["input_ids"].shape[-1]

>>> outputs = model.generate(**inputs, max_new_tokens=1024)
>>> print(processor.decode(outputs[0][input_len:], skip_special_tokens=False))

Inkling2ImageProcessor

클래스 transformers.Inkling2ImageProcessor

< >

( **kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> )

매개변수

  • do_convert_rgb (bool, kwargs, 선택 사항, 기본값 True) — 이미지를 RGB로 변환할지 여부.
  • do_resize (bool, kwargs, 선택) — 이미지를 리사이즈할지 여부.
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs, 기본값 {'height' -- 40, 'width': 40}): 모델에 입력되는 최대 차원을 설명합니다.
  • default_to_square (bool, kwargs, 선택 사항, 기본값 True) — size가 int인 경우 리사이즈 시 정사각형 이미지로 기본 설정할지 여부입니다.
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — center_crop을 적용한 후 출력 이미지의 크기.
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 이미지를 리사이즈할 경우 사용할 리샘플링 필터입니다. 이는 PILImageResampling enum 중 하나일 수 있습니다. do_resize가 True로 설정된 경우에만 효과가 있습니다.
  • do_rescale (bool, kwargs, 선택, 기본값 True) — 이미지를 다시 스케일링할지 여부.
  • rescale_factor (float, kwargs, 선택 사항, 기본값 0.00392156862745098) — do_rescale이 True로 설정된 경우 이미지를 재조정(rescale)하는 데 사용할 재조정 계수입니다.
  • do_normalize (bool, kwargs, 선택, 기본값 True) — 이미지를 정규화할지 여부.
  • image_mean (Union[float, list[float], tuple[float, ...]], kwargs, 선택, 기본값 [0.5, 0.5, 0.5]) — 정규화에 사용할 이미지 평균입니다. do_normalize가 True로 설정된 경우에만 효과가 있습니다.
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 선택, 기본값 [0.5, 0.5, 0.5]) — 정규화에 사용할 이미지 표준 편차. do_normalize가 True로 설정된 경우에만 효과가 있습니다.
  • do_pad (bool, kwargs, optional) — 이미지를 패딩할지 여부입니다. 패딩은 배치 내 가장 큰 크기로 수행하거나, 이미지마다 고정된 정사각형 크기로 수행합니다. 정확한 패딩 전략은 모델에 따라 달라집니다.
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 이미지를 패딩할 {"height": int, "width" int} 크기를 지정합니다. 전처리용으로 제공된 모든 이미지 크기보다 커야 합니다. pad_size가 제공되지 않으면, 배치 내 가장 큰 높이와 너비로 패딩됩니다. do_pad=True.일 때만 적용됩니다.
  • do_center_crop (bool, kwargs, 선택) — 이미지를 중앙으로 크롭할지 여부.
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 선택 사항) — ChannelDimension.FIRST만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다.
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 선택 사항) — 입력 이미지의 채널 차원 형식입니다. 설정되지 않으면 입력 이미지에서 채널 차원 형식을 추론합니다. 다음 중 하나일 수 있습니다:
    • "channels_first" 또는 ChannelDimension.FIRST: (num_channels, height, width) 형식의 이미지.
    • "channels_last" 또는 ChannelDimension.LAST: (height, width, num_channels) 형식의 이미지.
    • "none" 또는 ChannelDimension.NONE: (height, width) 형식의 이미지.
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 동영상을 처리할 장치입니다. 설정되지 않은 경우, 입력 동영상에서 장치를 추론합니다.
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 'pt'로 설정된 경우 스택된 텐서를 반환하고, 그렇지 않으면 텐서 목록을 반환합니다.
  • disable_grouping (bool, kwargs, 선택 사항) — 이미지를 크기에 따라 그룹화하는 것을 비활성화하여 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.
  • image_seq_length (int, kwargs, 선택) — 입력에서 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다. 'pt'로 설정된 경우 스택된 텐서를 반환하고, 그렇지 않으면 텐서 목록을 반환합니다.
  • disable_grouping (bool, kwargs, 선택 사항) — 이미지를 크기에 따라 그룹화하는 것을 비활성화하여 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.
  • image_seq_length (int, kwargs, 선택 사항) — 입력에서 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.
  • Returns 'pt'로 설정된 경우 스택된 텐서를 반환하고, 그렇지 않으면 텐서 목록을 반환합니다. —

Inkling2 이미지 프로세서 객체를 생성합니다.

disable_grouping (bool, kwargs, 선택): 이미지를 크기로 그룹화하는 것을 비활성화하여 배치 대신 개별적으로 처리할지 여부. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다. image_seq_length (int, kwargs, 선택): 입력에서 각 이미지에 사용할 이미지 토큰의 수. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.

Inkling2Processor

클래스 transformers.Inkling2Processor

< >

( image_processor = Nonetokenizer = Nonechat_template = Noneimage_token = '<|unused_200054|>' )

매개변수

  • image_processor (Inkling2ImageProcessor) — 이미지 프로세서가 필수 입력입니다.
  • tokenizer (tokenizer_class) — 토크나이저는 필수 입력값입니다.
  • chat_template (str) — 채팅의 메시지 목록을 토큰화 가능한 문자열로 변환하는 Jinja 템플릿입니다.
  • image_token (str, 선택 사항, 기본값 "<|unused_200054|>") — 각 이미지 소프트 토큰 슬롯에 대한 플레이스홀더 토큰이며, 이미지 특징으로 대체됩니다.

이미지 프로세서와 토크나이저를 단일 프로세서로 래핑하는 Inkling2Processor를 생성합니다.

Inkling2Processor는 Inkling2ImageProcessor와 tokenizer_class의 모든 기능을 제공합니다. 자세한 내용은 ~Inkling2ImageProcessor와 ~tokenizer_class를 참고하세요.

Update on GitHub