Transformers documentation

Qwen3-Omni-MOE

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

and get access to the augmented documentation experience

to get started

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

Qwen3-Omni-MOE

FlashAttention SDPA

개요

Qwen3-Omni-MOE 모델은 Alibaba Group의 Qwen 팀이 Qwen3-Omni Technical Report에서 제안한 통합 멀티모달 모델입니다.

기술 보고서의 초록은 다음과 같습니다:

*Qwen3-Omni를 소개합니다. Qwen3-Omni는 텍스트, 이미지, 오디오, 비디오 전반에서 단일 모달 모델 대비 성능 저하 없이 최첨단 성능을 유지하는 단일 멀티모달 모델입니다. Qwen3-Omni는 Qwen 시리즈 내 동일 크기의 단일 모달 모델과 동등한 성능을 보이며, 특히 오디오 작업에서 뛰어난 성능을 발휘합니다. 36개의 오디오 및 오디오-비주얼 벤치마크에서 Qwen3-Omni는 32개 벤치마크에서 오픈소스 SOTA, 22개 벤치마크에서 전체 SOTA를 달성하여 Gemini-2.5-Pro, Seed-ASR, GPT-4o-Transcribe와 같은 강력한 클로즈드소스 모델을 능가합니다. Qwen3-Omni는 텍스트, 이미지, 오디오, 비디오에 걸친 인식과 생성을 통합하는 Thinker-Talker MoE 아키텍처를 채택하여 유창한 텍스트와 자연스러운 실시간 음성 생성을 제공합니다. 119개 언어의 텍스트 상호작용, 19개 언어의 음성 이해, 10개 언어의 음성 생성을 지원합니다. 스트리밍 합성 시 첫 패킷 지연을 줄이기 위해, Talker는 멀티 코드북 스키마를 사용하여 이산 음성 코덱을 자기회귀적으로 예측합니다. 이러한 코드북의 표현 역량을 활용하여, 계산 집약적인 블록 단위 확산을 경량 causal ConvNet으로 대체하여 첫 번째 코덱 프레임부터 스트리밍을 가능하게 했습니다. 콜드 스타트 환경에서 Qwen3-Omni는 234ms의 이론적 엔드투엔드 첫 패킷 지연을 달성합니다. 멀티모달 추론을 한층 강화하기 위해, 모든 모달의 입력에 대해 명시적으로 추론하는 Thinking 모델을 도입했습니다. 현재 연구 커뮤니티에 범용 오디오 캡셔닝 모델이 부재하므로, Qwen3-Omni-30B-A3B를 파인튜닝하여 Qwen3-Omni-30B-A3B-Captioner를 확보했습니다. 이 모델은 임의의 오디오 입력에 대해 상세하고 환각이 적은 캡션을 생성합니다. Qwen3-Omni-30B-A3B, Qwen3-Omni-30B-A3B-Thinking, Qwen3-Omni-30B-A3B-Captioner는 Apache 2.0 라이선스 하에 공개되었습니다.

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

  • Qwen3OmniMoeForConditionalGeneration을 사용하여 오디오와 텍스트 출력을 생성합니다. 출력 유형을 하나만 생성하려면, 텍스트 전용에는 Qwen3OmniMoeThinkerForConditionalGeneration을, 오디오 전용에는 Qwen3OmniMoeTalkerForConditionalGeneration을 사용합니다.
  • 비디오 입력을 처리할 때 메모리 부족 오류가 발생하면 processor.max_pixels 값을 줄이세요. 기본적으로 최대값은 매우 큰 값으로 설정되어 있어, 해상도가 processor.max_pixels를 초과하지 않는 한 고해상도 시각 자료는 리사이즈되지 않습니다.
  • 프로세서에는 채팅 메시지를 모델 입력으로 변환하기 위한 자체 apply_chat_template() 메서드가 있습니다.

사용 예시

Qwen3-Omni는 Huggingface Hub에서 찾을 수 있습니다.

단일 미디어 추론

모델은 텍스트, 이미지, 오디오, 비디오를 입력으로 받을 수 있습니다. 추론을 위한 예제 코드는 다음과 같습니다.

import soundfile as sf

from transformers import Qwen3OmniMoeForConditionalGeneration, Qwen3OmniMoeProcessor


model = Qwen3OmniMoeForConditionalGeneration.from_pretrained(
    "Qwen/Qwen3-Omni-30B-A3B-Instruct",
    device_map="auto"
)
processor = Qwen3OmniMoeProcessor.from_pretrained("Qwen/Qwen3-Omni-30B-A3B-Instruct")

conversations = [
    {
        "role": "system",
        "content": [
            {"type": "text", "text": "You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, capable of perceiving auditory and visual inputs, as well as generating text and speech."}
        ],
    },
    {
        "role": "user",
        "content": [
            {"type": "video", "video": "/path/to/video.mp4"},
            {"type": "text", "text": "What can't you hear and see in this video?"},
        ],
    },
]

inputs = processor.apply_chat_template(
    conversations,
    load_audio_from_video=True,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    fps=1,

    # kwargs to be passed to `Qwen3OmniMoeProcessor`
    padding=True,
    use_audio_in_video=True,
).to(model.device)

# Generation params for audio or text can be different and have to be prefixed with `thinker_` or `talker_`
text_ids, audio = model.generate(**inputs, use_audio_in_video=True, thinker_do_sample=False, talker_do_sample=True)
text = processor.batch_decode(text_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)

sf.write(
    "output.wav",
    audio.reshape(-1).detach().cpu().numpy(),
    samplerate=24000,
)
print(text)

텍스트 전용 생성

오디오 생성 모델을 로드하지 않고 컴퓨트 비용을 절감하면서 텍스트 출력만 생성하려면 Qwen3OmniMoeThinkerForConditionalGeneration 모델을 사용할 수 있습니다.

from transformers import Qwen3OmniMoeProcessor, Qwen3OmniMoeThinkerForConditionalGeneration


model = Qwen3OmniMoeThinkerForConditionalGeneration.from_pretrained(
    "Qwen/Qwen3-Omni-30B-A3B-Instruct",
    device_map="auto",
)
processor = Qwen3OmniMoeProcessor.from_pretrained("Qwen/Qwen3-Omni-30B-A3B-Instruct")

conversations = [
    {
        "role": "system",
        "content": [
            {"type": "text", "text": "You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, capable of perceiving auditory and visual inputs, as well as generating text and speech."}
        ],
    },
    {
        "role": "user",
        "content": [
            {"type": "video", "video": "/path/to/video.mp4"},
            {"type": "text", "text": "What can't you hear and see in this video?"},
        ],
    },
]

inputs = processor.apply_chat_template(
    conversations,
    load_audio_from_video=True,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    fps=1,

    # kwargs to be passed to `Qwen3OmniMoeProcessor`
    padding=True,
    use_audio_in_video=True,
).to(model.device)


text_ids = model.generate(**inputs, use_audio_in_video=True)
text = processor.batch_decode(text_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)

print(text)

배치 혼합 미디어 추론

Qwen3OmniMoeThinkerForConditionalGeneration 모델을 사용할 때, 텍스트, 이미지, 오디오, 비디오 등 다양한 유형의 혼합 샘플로 구성된 입력을 배치로 처리할 수 있습니다. 아래는 예시입니다.

import soundfile as sf
from transformers import Qwen3OmniMoeForConditionalGeneration, Qwen3OmniMoeProcessor

model = Qwen3OmniMoeForConditionalGeneration.from_pretrained(
    "Qwen/Qwen3-Omni-30B-A3B-Instruct",
    device_map="auto"
)
processor = Qwen3OmniMoeProcessor.from_pretrained("Qwen/Qwen3-Omni-30B-A3B-Instruct")

# Conversation with video only
conversation1 = [
    {
        "role": "system",
        "content": [
            {"type": "text", "text": "You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, capable of perceiving auditory and visual inputs, as well as generating text and speech."}
        ],
    },
    {
        "role": "user",
        "content": [
            {"type": "video", "path": "/path/to/video.mp4"},
        ]
    }
]

# Conversation with audio only
conversation2 = [
    {
        "role": "system",
        "content": [
            {"type": "text", "text": "You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, capable of perceiving auditory and visual inputs, as well as generating text and speech."}
        ],
    },
    {
        "role": "user",
        "content": [
            {"type": "audio", "path": "/path/to/audio.wav"},
        ]
    }
]

# Conversation with pure text
conversation3 = [
    {
        "role": "system",
        "content": [
            {"type": "text", "text": "You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, capable of perceiving auditory and visual inputs, as well as generating text and speech."}
        ],
    },
    {
        "role": "user",
        "content": [{"type": "text", "text": "who are you?"}],
    }
]


# Conversation with mixed media
conversation4 = [
    {
        "role": "system",
        "content": [
            {"type": "text", "text": "You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, capable of perceiving auditory and visual inputs, as well as generating text and speech."}
        ],
    },
    {
        "role": "user",
        "content": [
            {"type": "image", "path": "/path/to/image.jpg"},
            {"type": "video", "path": "/path/to/video.mp4"},
            {"type": "audio", "path": "/path/to/audio.wav"},
            {"type": "text", "text": "What are the elements can you see and hear in these media?"},
        ],
    }
]

conversations = [conversation1, conversation2, conversation3, conversation4]

inputs = processor.apply_chat_template(
    conversations,
    load_audio_from_video=True,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    fps=1,

    # kwargs to be passed to `Qwen3OmniMoeProcessor`
    padding=True,
    use_audio_in_video=True,
).to(model.thinker.device)

text_ids = model.generate(**inputs, use_audio_in_video=True)
text = processor.batch_decode(text_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)

print(text)

Batch audio generation

Qwen3OmniMoeForConditionalGeneration는 배치 오디오 출력 생성을 지원합니다. 예를 들어, 텍스트-음성 변환 배치 생성이 있습니다. 샘플이 하나 이상인 배치의 경우, 생성된 오디오는 샘플당 하나의 웨이브폼을 가진 리스트로 반환되며, 각 웨이브폼은 해당 샘플의 길이에 맞게 이미 잘려 있습니다. 따라서 짧은 샘플에 불필요한 오디오가 패딩되지 않습니다. 단일 샘플 호출의 경우에도 여전히 하나의 텐서가 반환됩니다.

import soundfile as sf
from transformers import AutoModelForTextToWaveform, AutoProcessor
import torch

model_id = "Qwen/Qwen3-Omni-30B-A3B-Instruct"
model = AutoModelForTextToWaveform.from_pretrained(model_id, device_map="auto")
processor = AutoProcessor.from_pretrained(model_id)
sampling_rate = 24000  # output sampling rate
max_new_tokens = 128  # maximum number of tokens to generate

system_text = (
    "You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, capable of "
    "perceiving auditory and visual inputs, as well as generating text and speech."
)
texts = [
    "Hello, I'm Qwen. How can I help you today? Just let me know!",
    "The weather is nice today.",
]
inputs = processor.apply_chat_template(
    [
        [
            {"role": "system", "content": [{"type": "text", "text": system_text}]},
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": (
                            "Please read the following text aloud exactly as written, with no "
                            f"additional commentary:\n\n{text}"
                        ),
                    }
                ],
            },
        ]
        for text in texts
    ],
    tokenize=True,
    add_generation_prompt=True,
    return_dict=True,
    return_tensors="pt",
    processor_kwargs={"padding": True},
).to(model.device, dtype=model.dtype)

gen_kwargs = {
    "talker_do_sample": True,
    "speaker": "Ethan",     # Ethan, Chelsie
    "talker_max_new_tokens": max_new_tokens,
}
_, pred_waveform = model.generate(**inputs, **gen_kwargs)

for sample_id, audio in enumerate(pred_waveform):
    sf.write(f"qwen3_omni_output_{sample_id}.wav", audio.detach().to(torch.float32).cpu().numpy(), sampling_rate)
    print(f"Saved audio to qwen3_omni_output_{sample_id}.wav")

사용 팁

이미지 해상도 트레이드오프

모델은 다양한 해상도의 입력을 지원합니다. 기본적으로 입력에 네이티브 해상도를 사용하지만, 더 높은 해상도를 사용하면 계산 비용이 증가하는 대신 성능을 향상시킬 수 있습니다. 사용자는 필요에 맞는 최적의 구성을 위해 최소 및 최대 픽셀 수를 설정할 수 있습니다.

min_pixels = 128*28*28
max_pixels = 768*28*28
processor = AutoProcessor.from_pretrained("Qwen/Qwen3-Omni-30B-A3B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels)

음성 출력을 위한 프롬프트

사용자가 오디오 출력을 필요로 하는 경우, 시스템 프롬프트를 “Qwen은 Alibaba Group의 Qwen Team에서 개발한 가상 인간으로, 청각 및 시각 입력을 인지하고 텍스트와 음성 생성이 가능합니다.”로 설정해야 합니다. 그렇지 않으면 오디오 출력이 의도대로 작동하지 않을 수 있습니다.

{
    "role": "system",
    "content": "You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, capable of perceiving auditory and visual inputs, as well as generating text and speech.",
}

음성 출력을 사용할지 여부

모델은 텍스트와 오디오 출력을 모두 지원합니다. 오디오 출력이 필요하지 않은 경우 from_pretrained 함수에서 enable_audio_output를 설정할 수 있습니다. 이 옵션을 사용하면 GPU 메모리를 약 ~2GB 절약할 수 있지만, generate 함수의 return_audio 옵션은 False로만 설정할 수 있습니다.

model = Qwen3OmniMoeForConditionalGeneration.from_pretrained(
    "Qwen/Qwen3-Omni-30B-A3B-Instruct",
    device_map="auto",
    enable_audio_output=False,
)

유연한 경험을 위해, from_pretrained 함수를 통해 모델을 초기화할 때 enable_audio_output을 True로 설정하고, generate 함수가 호출될 때 오디오를 반환할지 여부를 결정하는 것을 권장합니다. return_audio가 False로 설정되면, 모델은 텍스트 응답을 더 빠르게 얻기 위해 텍스트 출력만 반환합니다.

model = Qwen3OmniMoeForConditionalGeneration.from_pretrained(
    "Qwen/Qwen3-Omni-30B-A3B-Instruct",
    device_map="auto",
    enable_audio_output=True,
)
...
text_ids = model.generate(**inputs, return_audio=False)

출력 오디오의 음성 유형 변경

Qwen3-Omni-MOE는 출력 오디오의 음성을 변경할 수 있는 기능을 지원합니다. 사용자는 generate 함수의 speaker 매개변수를 사용하여 음성 유형을 지정할 수 있습니다. "Qwen/Qwen3-Omni-30B-A3B-Instruct" 체크포인트는 Chelsie와 Ethan 두 가지 음성 유형을 지원하며, Chelsie는 여성 음성이고 Ethan은 남성 음성입니다. 기본적으로 speaker가 지정되지 않으면 기본 음성 유형은 Chelsie입니다.

text_ids, audio = model.generate(**inputs, speaker="Chelsie")
text_ids, audio = model.generate(**inputs, speaker="Ethan")

생성 속도를 높이기 위한 Flash-Attention 2

먼저 Flash Attention 2의 최신 버전을 설치했는지 확인하세요:

pip install -U flash-attn --no-build-isolation

또한 FlashAttention 2와 호환되는 하드웨어가 있어야 합니다. flash attention 저장소의 공식 문서에서 자세한 내용을 확인하세요. FlashAttention-2는 모델이 torch.float16 또는 torch.bfloat16로 로드된 경우에만 사용할 수 있습니다.

FlashAttention-2를 사용하여 모델을 로드하고 실행하려면, 모델을 로드할 때 attn_implementation="flash_attention_2"를 추가하세요:

from transformers import Qwen3OmniMoeForConditionalGeneration


model = Qwen3OmniMoeForConditionalGeneration.from_pretrained(
    "Qwen/Qwen3-Omni-30B-A3B-Instruct",
    device_map="auto",
    attn_implementation="flash_attention_2",
)

Qwen3OmniMoeConfig

클래스 transformers.Qwen3OmniMoeConfig

< >

( 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 = Nonethinker_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetalker_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonecode2wav_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneenable_audio_output: bool = Trueim_start_token_id: int = 151644im_end_token_id: int = 151645tts_pad_token_id: int = 151671tts_bos_token_id: int = 151672tts_eos_token_id: int = 151673system_token_id: int = 8948user_token_id: int = 872assistant_token_id: int = 77091initializer_range: float | None = None )

매개변수

  • thinker_config (dict, 선택 사항) — 기저 thinker 서브모델의 설정입니다.
  • talker_config (dict, 선택 사항) — 기저 talker 서브모델의 설정입니다.
  • code2wav_config (dict, 선택) — 기저 code2wav 서브모델의 설정입니다.
  • enable_audio_output (bool, 선택 사항, 기본값 True) — 음성 출력을 활성화하고 talker 및 code2wav 모듈을 로드할지 여부.
  • im_start_token_id (int, 선택 사항, 기본값 151644) — 이미지 시작에 사용되는 토큰 ID
  • im_end_token_id (int, 선택 사항, 기본값 151645) — 이미지 종료에 사용되는 토큰 ID
  • tts_pad_token_id (int, 선택 사항, 기본값 151671) — TTS에서 패딩에 사용되는 토큰 ID
  • tts_bos_token_id (int, 선택 사항, 기본값 151672) — TTS에서 시퀀스 시작을 나타내는 토큰 ID
  • tts_eos_token_id (int, 선택 사항, 기본값 151673) — 이미지 TTS에서 시퀀스 종료에 사용되는 토큰 ID
  • system_token_id (int, 선택 사항, 기본값 8948) — 시스템 프롬프트에 사용되는 토큰 ID
  • user_token_id (int, 선택 사항, 기본값 872) — 사용자 프롬프트에 사용되는 토큰 ID
  • assistant_token_id (int, 선택 사항, 기본값 77091) — 어시스턴트 프롬프트에 사용되는 토큰 ID
  • initializer_range (float, 선택 사항) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.

이것은 Qwen3 Omni MoeModel의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 Qwen3 Omni Moe 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 인스턴스화하면 Qwen/Qwen3-Omni-30B-A3B-Instruct와 유사한 설정이 생성됩니다.

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

예:

>>> from transformers import (
...     Qwen3OmniMoeThinkerConfig,
...     Qwen3OmniMoeTalkerConfig,
...     Qwen3OmniMoeCode2WavConfig,
...     Qwen3OmniMoeForConditionalGeneration,
...     Qwen3OmniMoeConfig,
... )

>>> # Initializing a Qwen3OmniMoe style configuration
>>> configuration = Qwen3OmniMoeConfig()

>>> # Initializing a model from the configuration
>>> model = Qwen3OmniMoeForConditionalGeneration(configuration)

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

get_text_config

< >

( decoder = False )

매개변수

  • decoder (Optional[bool], 선택 사항, 기본값 False) — True로 설정하면 decoder 설정 이름만 검색합니다.

텍스트 IO에 사용하도록 의도된 config를 반환합니다. 대부분의 모델에서는 원래의 config 인스턴스 자체입니다. 특정 복합 모델의 경우, 유효한 이름 집합 아래에 위치합니다.

Qwen3OmniMoeThinkerConfig

class transformers.Qwen3OmniMoeThinkerConfig

< >

( 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 = Noneaudio_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneposition_id_per_seconds: int = 25audio_start_token_id: int = 151647user_token_id: int = 872initializer_range: float = 0.02tie_word_embeddings: bool = Falseaudio_token_id: int = 151646image_token_id: int = 151655video_token_id: int = 151656 )

매개변수

  • audio_config (Union[dict, ~configuration_utils.PreTrainedConfig], 선택) — 오디오 백본의 config 객체 또는 사전입니다.
  • vision_config (Union[dict, ~configuration_utils.PreTrainedConfig], 선택) — 비전 백본의 config 객체 또는 사전입니다.
  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig], 선택) — 텍스트 백본의 config 객체 또는 사전입니다.
  • position_id_per_seconds (int, 선택 사항, 기본값 25) — 초당 position id 증가량입니다.
  • audio_start_token_id (int, 선택 사항, 기본값 151647) — 오디오 프롬프트를 인코딩할 때 사용할 오디오 시작 토큰 ID입니다.
  • user_token_id (int, 선택 사항, 기본값 872) — 사용자 토큰을 인코딩할 사용자 토큰 ID입니다.
  • initializer_range (float, 선택 사항, 기본값 0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.
  • tie_word_embeddings (bool, 선택, 기본값 False) — 모델의 tied_weights_keys 매핑에 따라 가중치 임베딩을 묶을지 여부.
  • audio_token_id (int, 선택 사항, 기본값 151646) — 입력 오디오를 위한 플레이스홀더로 사용되는 오디오 토큰 인덱스입니다.
  • image_token_id (int, 선택 사항, 기본값 151655) — 입력 이미지의 플레이스홀더로 사용되는 이미지 토큰 인덱스입니다.
  • video_token_id (int, 선택 사항, 기본값 151656) — 입력 비디오의 플레이스홀더로 사용되는 비디오 토큰 인덱스입니다.

이것은 Qwen3 Omni MoeModel의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 Qwen3 Omni Moe 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 인스턴스화하면 Qwen/Qwen3-Omni-30B-A3B-Instruct와 유사한 설정이 생성됩니다.

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

예:

>>> from transformers import Qwen3OmniMoeThinkerModel, Qwen3OmniMoeThinkerConfig

>>> # Initializing a default Qwen3OmniMoeThinkerConfig
>>> configuration = Qwen3OmniMoeThinkerConfig()

>>> # Initializing a model (with random weights) from the default configuration
>>> model = Qwen3OmniMoeThinkerModel(configuration)

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

Qwen3OmniMoeTalkerConfig

클래스 transformers.Qwen3OmniMoeTalkerConfig

< >

( 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 = Nonecode_predictor_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonenum_code_groups: int = 32thinker_hidden_size: int = 2048codec_eos_token_id: int = 4198accept_hidden_layer: int = 18codec_nothink_id: int = 4203codec_think_bos_id: int = 4204codec_think_eos_id: int = 4205codec_pad_id: int = 4196codec_bos_id: int = 4197audio_token_id: int = 151646image_token_id: int = 151655video_token_id: int = 151656vision_start_token_id: int = 151652position_id_per_seconds: int = 25audio_start_token_id: int = 151669speaker_id: dict | None = Noneinitializer_range: float = 0.02tie_word_embeddings: bool = False )

매개변수

  • code_predictor_config (dict, 선택) — Qwen3OmniMoeTalkerCodePredictorConfig를 초기화하는 데 사용되는 설정 매개변수 사전입니다. 제공되지 않으면 기본값이 사용됩니다.
  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig], 선택) — 텍스트 백본의 config 객체 또는 사전입니다.
  • num_code_groups (int, 선택 사항, 기본값 32) — 예측된 음향 토큰 시퀀스에서 사용되는 코드북 그룹의 수로, 멀티 코드북 VQ 표현에 해당합니다.
  • thinker_hidden_size (int, 선택 사항, 기본값 2048) — 음성 생성 전 중간 추론 또는 잠재적 계획에 사용되는 thinker 모듈의 숨겨진 차원 크기입니다.
  • codec_eos_token_id (int, 선택 사항, 기본값 4198) — codec 생성 시퀀스에서 음성 종료(end-of-speech) 토큰을 나타내는 토큰 ID입니다.
  • accept_hidden_layer (int, 선택 사항, 기본값 18) — think-and-speak 과정에서 생성된 토큰을 수용하거나 개선하는 데 사용되는 hidden layer의 인덱스입니다.
  • codec_nothink_id (int, 선택 사항, 기본값 4203) — 생성 과정에서 사고 단계가 필요 없음을 나타내는 토큰 ID입니다.
  • codec_think_bos_id (int, 선택 사항, 기본값 4204) — 생각 시퀀스의 시작을 나타내는 토큰 ID입니다.
  • codec_think_eos_id (int, 선택 사항, 기본값 4205) — 생각 시퀀스의 끝을 나타내는 토큰 ID입니다.
  • codec_pad_id (int, 선택 사항, 기본값 4196) — Codec 입력 시퀀스에서 사용되는 패딩 토큰 ID입니다.
  • codec_bos_id (int, 선택 사항, 기본값 4197) — codec 시퀀스에서 음성 시작을 나타내는 토큰 ID입니다.
  • audio_token_id (int, 선택 사항, 기본값 151646) — 입력 오디오를 위한 플레이스홀더로 사용되는 오디오 토큰 인덱스입니다.
  • image_token_id (int, 선택 사항, 기본값 151655) — 입력 이미지의 플레이스홀더로 사용되는 이미지 토큰 인덱스입니다.
  • video_token_id (int, 선택 사항, 기본값 151656) — 입력 비디오의 플레이스홀더로 사용되는 비디오 토큰 인덱스입니다.
  • vision_start_token_id (int, 선택 사항, 기본값 151652) — 멀티모달 입력 시퀀스에서 시각 세그먼트의 시작을 나타내는 토큰 ID입니다.
  • position_id_per_seconds (int, 선택 사항, 기본값 25) — 생성 시 시간 정렬에 사용되는 오디오 콘텐츠 1초당 할당되는 position ID의 수입니다.
  • audio_start_token_id (int, 선택 사항, 기본값 151669) — 출력에서 오디오 생성 세그먼트의 시작을 나타내는 토큰 ID입니다.
  • speaker_id (dict, 선택 사항) — 스피커 이름에서 스피커 ID로 매핑된 dict.
  • initializer_range (float, 선택 사항, 기본값 0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.
  • tie_word_embeddings (bool, 선택, 기본값 False) — 모델의 tied_weights_keys 매핑에 따라 가중치 임베딩을 묶을지 여부.

이것은 Qwen3 Omni MoeModel의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 Qwen3 Omni Moe 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 인스턴스화하면 Qwen/Qwen3-Omni-30B-A3B-Instruct와 유사한 설정이 생성됩니다.

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

예:

>>> from transformers import Qwen3OmniMoeTalkerConfig, Qwen3OmniMoeTalker

>>> # Initialize a Qwen3OmniMoeTalkerConfig with default sub-configurations
>>> config = Qwen3OmniMoeTalkerConfig(
...     num_code_groups=32,
...     thinker_hidden_size=2048,
... )

>>> # Initialize the full Qwen3-Omni Talker model
>>> model = Qwen3OmniMoeTalker(config)

>>> # Access the model configuration
>>> config = model.config
>>> print(config.text_config)  # Access text decoder configuration
>>> print(config.code_predictor_config)  # Access code predictor configuration

Qwen3OmniMoeTextConfig

class transformers.Qwen3OmniMoeTextConfig

< >

( 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 = 3584hidden_size: int = 2048intermediate_size: int = 18944num_hidden_layers: int = 28num_attention_heads: int = 28num_key_value_heads: int = 4hidden_act: str = 'silu'max_position_embeddings: int = 32768initializer_range: float = 0.02rms_norm_eps: float = 1e-06use_cache: bool = Truerope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Noneattention_bias: bool = Falsesliding_window: int | None = Noneattention_dropout: float | int = 0.0decoder_sparse_step: int = 1moe_intermediate_size: int = 768num_experts_per_tok: int = 8num_experts: int = 128norm_topk_prob: bool = Trueoutput_router_logits: bool = Falserouter_aux_loss_coef: float = 0.001mlp_only_layers: list[int] | None = Nonepad_token_id: int | None = Nonebos_token_id: int | None = Noneeos_token_id: int | list[int] | None = None )

매개변수

  • vocab_size (int, 선택 사항, 기본값 3584) — 모델의 어휘 크기입니다. input_ids로 표현할 수 있는 서로 다른 토큰의 수를 정의합니다.
  • hidden_size (int, 선택 사항, 기본값 2048) — 숨겨진 표현의 차원입니다.
  • intermediate_size (int, 선택 사항, 기본값 18944) — MLP 표현의 차원입니다.
  • num_hidden_layers (int, 선택 사항, 기본값 28) — Transformer decoder의 숨겨진 레이어 수.
  • num_attention_heads (int, 선택 사항, 기본값 28) — 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가 기본값으로 사용됩니다.
  • hidden_act (str, 선택 사항, 기본값 silu) — 디코더의 비선형 활성화 함수(함수 또는 문자열)입니다. 예를 들어, "gelu", "relu", "silu" 등이 있습니다.
  • max_position_embeddings (int, 선택 사항, 기본값 32768) — 이 모델이 사용될 수 있는 최대 시퀀스 길이입니다.
  • 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 생성 모델인 경우에만 관련이 있습니다.
  • rope_parameters (Union[~modeling_rope_utils.RopeParameters, dict], 선택) — RoPE 임베딩의 구성 매개변수를 포함하는 사전입니다. 사전에는 rope_theta 값이 포함되어야 하며, 더 긴 max_position_embeddings로 RoPE를 사용하려는 경우 스케일링에 사용되는 매개변수를 선택적으로 포함할 수 있습니다.
  • attention_bias (bool, 선택 사항, 기본값 False) — 자기 주의(self-attention) 시 query, key, value 및 출력 투영 계층에 bias를 사용할지 여부입니다.
  • sliding_window (int, 선택 사항) — 슬라이딩 윈도우 어텐션의 윈도우 크기입니다. None인 경우 슬라이딩 윈도우가 적용되지 않습니다.
  • attention_dropout (Union[float, int], 선택 사항, 기본값 0.0) — Attention 확률에 적용할 dropout 비율입니다.
  • decoder_sparse_step (int, 선택 사항, 기본값 1) — MoE 레이어의 빈도입니다.
  • moe_intermediate_size (int, 선택 사항, 기본값 768) — 라우팅된 전문가 MLP의 중간 크기입니다.
  • num_experts_per_tok (int, 선택 사항, 기본값 8) — 각 토큰을 라우팅할 전문가의 수입니다. 이는 토큰 선택 라우팅의 top-k 값입니다.
  • num_experts (int, 선택 사항, 기본값 128) — MoE 레이어의 라우팅 전문가 수입니다.
  • norm_topk_prob (bool, 선택 사항, 기본값 True) — 라우팅된 전문가의 가중치를 정규화할지 여부입니다.
  • output_router_logits (bool, 선택 사항, 기본값 False) — 모델이 router logits를 반환할지 여부입니다. 이 옵션을 활성화하면 load balancing loss와 router z-loss를 포함한 auxiliary loss도 출력할 수 있습니다.
  • router_aux_loss_coef (float, 선택 사항, 기본값 0.001) — 보조 로드 밸런싱 손실 계수입니다. MoE 모델에서 불균형한 전문가 라우팅을 처벌하는 데 사용됩니다.
  • mlp_only_layers (list[int], 선택 사항, 기본값 []) — Qwen3OmniMoeTextSparseMoeBlock 대신 Qwen3OmniMoeTextMLP를 사용하는 레이어를 지정합니다. 목록에는 num_layers개의 레이어가 있을 경우 0부터 num_layers-1까지의 레이어 인덱스가 포함됩니다. mlp_only_layers가 비어 있으면 decoder_sparse_step를 사용하여 희소성을 결정합니다.
  • pad_token_id (int, 선택 사항) — 어휘에서 패딩에 사용되는 토큰 ID입니다.
  • bos_token_id (int, 선택 사항) — 어휘에서 스트림 시작에 사용되는 토큰 ID입니다.
  • eos_token_id (Union[int, list[int]], 선택) — 어휘에서 스트림 종료에 사용되는 토큰 ID입니다.

이것은 Qwen3 Omni MoeModel의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 Qwen3 Omni Moe 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 인스턴스화하면 Qwen/Qwen3-Omni-30B-A3B-Instruct와 유사한 설정이 생성됩니다.

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

>>> from transformers import Qwen3OmniMoeTextModel, Qwen3OmniMoeTextConfig

>>> # Initializing a Qwen3OmniMoeText style configuration
>>> configuration = Qwen3OmniMoeTextConfig()

>>> # Initializing a model from the Qwen3-15B-A2B" style configuration
>>> model = Qwen3OmniMoeTextModel(configuration)

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

Qwen3OmniMoeVisionEncoderConfig

클래스 transformers.Qwen3OmniMoeVisionEncoderConfig

< >

( 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 = Nonedepth: int = 27hidden_size: int = 1152hidden_act: str = 'gelu_pytorch_tanh'intermediate_size: int = 4304num_heads: int = 16in_channels: int = 3patch_size: int | list[int] | tuple[int, int] = 16spatial_merge_size: int = 2temporal_patch_size: int | list[int] | tuple[int, int] = 2out_hidden_size: int = 3584num_position_embeddings: int = 2304deepstack_visual_indexes: list[int] | tuple[int, ...] = (8, 16, 24)initializer_range: float = 0.02rope_parameters: dict | None = None )

매개변수

  • depth (int, 선택 사항, 기본값 27) — 비전 인코더의 Transformer 레이어 수입니다.
  • hidden_size (int, 선택 사항, 기본값 1152) — 숨겨진 표현의 차원입니다.
  • hidden_act (str, 선택 사항, 기본값 gelu_pytorch_tanh) — 디코더에서 사용되는 비선형 활성화 함수(함수 또는 문자열)입니다. 예를 들어, "gelu", "relu", "silu" 등이 있습니다.
  • intermediate_size (int, 선택 사항, 기본값 4304) — MLP 표현의 차원입니다.
  • num_heads (int, 선택 사항, 기본값 16) — Transformer decoder의 각 attention layer에 사용할 attention head의 수입니다.
  • in_channels (int, 선택 사항, 기본값 3) — 입력 채널의 수입니다.
  • patch_size (Union[int, list[int], tuple[int, int]], 선택 사항, 기본값 16) — 각 패치의 크기(해상도)입니다.
  • spatial_merge_size (int, 선택 사항, 기본값 2) — 인접한 패치를 병합하여 시각 토큰의 수를 줄이는 데 사용되는 공간 병합 윈도우의 크기입니다.
  • temporal_patch_size (Union[int, list[int], tuple[int, int]], 선택 사항, 기본값 2) — 비디오 입력에 사용되는 3D 패치 임베딩에서 적용되는 시간적 패치 크기입니다.
  • out_hidden_size (int, 선택 사항, 기본값 3584) — 비전 모델의 출력 hidden size입니다.
  • num_position_embeddings (int, 선택 사항, 기본값 2304) — 이 모델이 사용될 수 있는 최대 시퀀스 길이
  • deepstack_visual_indexes (list[int], 선택 사항, 기본값 [8, 16, 24]) — deepstack 임베딩에 사용할 레이어의 인덱스입니다.
  • initializer_range (float, 선택 사항, 기본값 0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.
  • rope_parameters (dict, 선택) — RoPE 임베딩의 구성 매개변수를 포함하는 사전입니다. 사전에는 rope_theta 값이 포함되어야 하며, 더 긴 max_position_embeddings로 RoPE를 사용하려는 경우 스케일링에 사용되는 매개변수를 선택적으로 포함할 수 있습니다.

이것은 Qwen3 Omni MoeModel의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 Qwen3 Omni Moe 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 인스턴스화하면 Qwen/Qwen3-Omni-30B-A3B-Instruct와 유사한 설정이 생성됩니다.

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

Qwen3OmniMoeAudioEncoderConfig

클래스 transformers.Qwen3OmniMoeAudioEncoderConfig

< >

( 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 = Nonenum_mel_bins: int = 128encoder_layers: int = 32encoder_attention_heads: int = 20encoder_ffn_dim: int = 5120d_model: int = 1280dropout: float | int = 0.0attention_dropout: float | int = 0.0activation_function: str = 'gelu'activation_dropout: float | int = 0.0scale_embedding: bool = Falseinitializer_range: float = 0.02max_source_positions: int = 1500n_window: int = 50output_dim: int = 3584n_window_infer: int = 800conv_chunksize: int = 500downsample_hidden_size: int = 480 )

매개변수

  • num_mel_bins (int, 선택 사항, 기본값 128) — 입력 프레임당 사용되는 mel 특징의 수입니다. AutoFeatureExtractor 클래스에서 사용된 값과 일치해야 합니다.
  • encoder_layers (int, 선택 사항, 기본값 32) — Transformer 인코더의 숨겨진 레이어 수입니다. 설정하지 않으면 num_layers와 동일한 값을 사용합니다.
  • encoder_attention_heads (int, 선택 사항, 기본값 20) — Transformer 인코더의 각 어텐션 레이어에 사용할 어텐션 헤드 수입니다.
  • encoder_ffn_dim (int, 선택 사항, 기본값 5120) — 인코더의 “중간” 레이어(일반적으로 feed-forward 레이어라고도 함)의 차원입니다.
  • d_model (int, 선택 사항, 기본값 1280) — 인코더 레이어와 풀러 레이어의 크기입니다.
  • dropout (Union[float, int], 선택 사항, 기본값 0.0) — 모든 dropout 레이어에 적용할 비율입니다.
  • attention_dropout (Union[float, int], 선택 사항, 기본값 0.0) — Attention 확률에 적용할 dropout 비율입니다.
  • activation_function (str, 선택 사항, 기본값 gelu) — 디코더에서 사용되는 비선형 활성화 함수(함수 또는 문자열)입니다. 예를 들어, "gelu", "relu", "silu" 등이 있습니다.
  • activation_dropout (Union[float, int], 선택 사항, 기본값 0.0) — 완전 연결 레이어 내부 활성화에 적용할 dropout 비율입니다.
  • scale_embedding (bool, 선택 사항, 기본값 False) — 임베딩을 sqrt(d_model)로 나누어 스케일링할지 여부.
  • initializer_range (float, 선택 사항, 기본값 0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.
  • max_source_positions (int, 선택 사항, 기본값 1500) — 입력의 최대 시퀀스 길이
  • n_window (int, 선택 사항, 기본값 50) — 윈도우의 개수
  • output_dim (int, 선택 사항, 기본값 3584) — 출력의 차원
  • n_window_infer (int, 선택 사항, 기본값 800) — 추론 시 사용할 윈도우의 개수
  • conv_chunksize (int, 선택 사항, 기본값 500) — 컨볼루션 레이어의 각 입력에 대한 청크 크기
  • downsample_hidden_size (int, 선택 사항, 기본값 480) — 다운샘플링 레이어의 hidden size

이것은 Qwen3 Omni MoeModel의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 Qwen3 Omni Moe 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 인스턴스화하면 Qwen/Qwen3-Omni-30B-A3B-Instruct와 유사한 설정이 생성됩니다.

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

Qwen3OmniMoeTalkerTextConfig

클래스 transformers.Qwen3OmniMoeTalkerTextConfig

< >

( 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 = 3072hidden_size: int = 1024intermediate_size: int = 2048num_hidden_layers: int = 20num_attention_heads: int = 16num_key_value_heads: int = 2hidden_act: str = 'silu'max_position_embeddings: int = 32768initializer_range: float = 0.02rms_norm_eps: float = 1e-06use_cache: bool = Truetie_word_embeddings: bool = Falserope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Noneattention_bias: bool = Falsesliding_window: int | None = Noneattention_dropout: float | int = 0.0decoder_sparse_step: int = 1moe_intermediate_size: int = 384num_experts_per_tok: int = 8num_experts: int = 128norm_topk_prob: bool = Falseoutput_router_logits: bool = Falserouter_aux_loss_coef: float = 0.001mlp_only_layers: list[int] | None = Nonepad_token_id: int | None = Nonebos_token_id: int | None = Noneeos_token_id: int | list[int] | None = None )

매개변수

  • vocab_size (int, 선택 사항, 기본값 3072) — 모델의 어휘 크기입니다. input_ids로 표현할 수 있는 서로 다른 토큰의 수를 정의합니다.
  • hidden_size (int, 선택 사항, 기본값 1024) — 숨겨진 표현의 차원입니다.
  • intermediate_size (int, 선택 사항, 기본값 2048) — MLP 표현의 차원입니다.
  • num_hidden_layers (int, 선택 사항, 기본값 20) — Transformer decoder의 hidden layer 수입니다.
  • num_attention_heads (int, 선택 사항, 기본값 16) — Transformer decoder의 각 attention layer에 사용할 attention head의 수입니다.
  • num_key_value_heads (int, 선택 사항, 기본값 2) — 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가 기본값으로 사용됩니다.
  • hidden_act (str, 선택 사항, 기본값 silu) — 디코더의 비선형 활성화 함수(함수 또는 문자열)입니다. 예를 들어, "gelu", "relu", "silu" 등이 있습니다.
  • max_position_embeddings (int, 선택 사항, 기본값 32768) — 이 모델이 사용될 수 있는 최대 시퀀스 길이입니다.
  • 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 생성 모델인 경우에만 관련이 있습니다.
  • tie_word_embeddings (bool, 선택, 기본값 False) — 모델의 tied_weights_keys 매핑에 따라 가중치 임베딩을 묶을지 여부.
  • rope_parameters (Union[~modeling_rope_utils.RopeParameters, dict], 선택) — RoPE 임베딩의 구성 매개변수를 포함하는 사전입니다. 사전에는 rope_theta 값이 포함되어야 하며, 더 긴 max_position_embeddings로 RoPE를 사용하려는 경우 스케일링에 사용되는 매개변수를 선택적으로 포함할 수 있습니다.
  • attention_bias (bool, 선택 사항, 기본값 False) — 자기 주의(self-attention) 시 query, key, value 및 출력 투영 계층에 bias를 사용할지 여부입니다.
  • sliding_window (int, 선택 사항) — 슬라이딩 윈도우 어텐션의 윈도우 크기입니다. None인 경우 슬라이딩 윈도우가 적용되지 않습니다.
  • attention_dropout (Union[float, int], 선택 사항, 기본값 0.0) — Attention 확률에 적용할 dropout 비율입니다.
  • decoder_sparse_step (int, 선택 사항, 기본값 1) — MoE 레이어의 빈도입니다.
  • moe_intermediate_size (int, 선택 사항, 기본값 384) — 라우팅된 전문가 MLP의 중간 크기입니다.
  • num_experts_per_tok (int, 선택 사항, 기본값 8) — 각 토큰을 라우팅할 전문가의 수입니다. 이는 토큰 선택 라우팅의 top-k 값입니다.
  • num_experts (int, 선택 사항, 기본값 128) — MoE 레이어의 라우팅 전문가 수입니다.
  • norm_topk_prob (bool, 선택 사항, 기본값 False) — 라우팅된 전문가의 가중치를 정규화할지 여부입니다.
  • output_router_logits (bool, 선택 사항, 기본값 False) — 모델이 router logits를 반환할지 여부입니다. 이 옵션을 활성화하면 load balancing loss와 router z-loss를 포함한 auxiliary loss도 출력할 수 있습니다.
  • router_aux_loss_coef (float, 선택 사항, 기본값 0.001) — 보조 로드 밸런싱 손실 계수입니다. MoE 모델에서 불균형한 전문가 라우팅을 처벌하는 데 사용됩니다.
  • mlp_only_layers (list[int], 선택 사항, 기본값 []) — Qwen3OmniMoeTalkerTextSparseMoeBlock 대신 Qwen3OmniMoeTalkerTextMLP를 사용하는 레이어를 지정합니다. 목록에는 num_layers개의 레이어가 있는 경우 0부터 num_layers-1까지의 레이어 인덱스가 포함됩니다. mlp_only_layers가 비어 있으면 decoder_sparse_step를 사용하여 희소성을 결정합니다.
  • pad_token_id (int, 선택 사항) — 어휘에서 패딩에 사용되는 토큰 ID입니다.
  • bos_token_id (int, 선택 사항) — 어휘에서 스트림 시작에 사용되는 토큰 ID입니다.
  • eos_token_id (Union[int, list[int]], 선택) — 어휘에서 스트림 종료에 사용되는 토큰 ID입니다.

이것은 Qwen3 Omni MoeModel의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 Qwen3 Omni Moe 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 인스턴스화하면 Qwen/Qwen3-Omni-30B-A3B-Instruct와 유사한 설정이 생성됩니다.

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

>>> from transformers import Qwen3OmniMoeTalkerTextModel, Qwen3OmniMoeTalkerTextConfig

>>> # Initializing a Qwen3OmniMoeTalkerText style configuration
>>> configuration = Qwen3OmniMoeTalkerTextConfig()

>>> # Initializing a model from the Qwen3-15B-A2B" style configuration
>>> model = Qwen3OmniMoeTalkerTextModel(configuration)

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

Qwen3OmniMoeTalkerCodePredictorConfig

클래스 transformers.Qwen3OmniMoeTalkerCodePredictorConfig

< >

( 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 = 2048hidden_size: int = 1024intermediate_size: int = 3072num_hidden_layers: int = 5num_attention_heads: int = 16num_key_value_heads: int = 8head_dim: int = 128hidden_act: str = 'silu'max_position_embeddings: int = 32768initializer_range: float = 0.02rms_norm_eps: float = 1e-06use_cache: bool = Truetie_word_embeddings: bool = Falserope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Noneattention_bias: bool = Falsesliding_window: int | None = Nonemax_window_layers: int = 28layer_types: list[str] | None = Noneattention_dropout: float | int = 0.0pad_token_id: int | None = Nonebos_token_id: int | None = Noneeos_token_id: int | list[int] | None = Nonenum_code_groups: int = 32 )

매개변수

  • vocab_size (int, 선택 사항, 기본값 2048) — 모델의 어휘 크기입니다. input_ids로 표현할 수 있는 서로 다른 토큰의 수를 정의합니다.
  • hidden_size (int, 선택 사항, 기본값 1024) — 숨겨진 표현의 차원입니다.
  • intermediate_size (int, 선택 사항, 기본값 3072) — MLP 표현의 차원입니다.
  • num_hidden_layers (int, 선택 사항, 기본값 5) — Transformer decoder의 hidden layer 수입니다.
  • num_attention_heads (int, 선택 사항, 기본값 16) — 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 값이 기본값으로 사용됩니다.
  • hidden_act (str, 선택 사항, 기본값 silu) — 디코더의 비선형 활성화 함수(함수 또는 문자열)입니다. 예를 들어, "gelu", "relu", "silu" 등이 있습니다.
  • max_position_embeddings (int, 선택 사항, 기본값 32768) — 이 모델이 사용될 수 있는 최대 시퀀스 길이입니다.
  • 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 생성 모델인 경우에만 관련이 있습니다.
  • tie_word_embeddings (bool, 선택, 기본값 False) — 모델의 tied_weights_keys 매핑에 따라 가중치 임베딩을 묶을지 여부.
  • rope_parameters (Union[~modeling_rope_utils.RopeParameters, dict], 선택) — RoPE 임베딩의 구성 매개변수를 포함하는 사전입니다. 사전에는 rope_theta 값이 포함되어야 하며, 더 긴 max_position_embeddings로 RoPE를 사용하려는 경우 스케일링에 사용되는 매개변수를 선택적으로 포함할 수 있습니다.
  • attention_bias (bool, 선택 사항, 기본값 False) — 자기 주의(self-attention) 시 query, key, value 및 출력 투영 계층에 bias를 사용할지 여부입니다.
  • sliding_window (int, 선택 사항) — 슬라이딩 윈도우 어텐션의 윈도우 크기입니다. None인 경우 슬라이딩 윈도우가 적용되지 않습니다.
  • max_window_layers (int, 선택 사항, 기본값 28) — 풀 어텐션을 사용하는 레이어의 수입니다. 처음 max_window_layers개의 레이어는 풀 어텐션을 사용하고, 그 이후의 추가 레이어는 SWA(Sliding Window Attention)를 사용합니다.
  • layer_types (list[str], 선택 사항) — 각 레이어 인덱스를 해당 레이어 유형에 명시적으로 매핑하는 목록입니다. 제공되지 않으면 config 값에 기반하여 자동으로 생성됩니다.
  • attention_dropout (Union[float, int], 선택 사항, 기본값 0.0) — Attention 확률에 적용할 dropout 비율입니다.
  • pad_token_id (int, 선택 사항) — 어휘에서 패딩에 사용되는 토큰 ID입니다.
  • bos_token_id (int, 선택 사항) — 어휘에서 스트림 시작에 사용되는 토큰 ID입니다.
  • eos_token_id (Union[int, list[int]], 선택) — 어휘에서 스트림 종료에 사용되는 토큰 ID입니다.
  • num_code_groups (int, 선택 사항, 기본값 32) — 예측된 음향 토큰 시퀀스에서 사용되는 코드북 그룹의 수로, 멀티 코드북 VQ 표현에 해당합니다.

이것은 Qwen3 Omni MoeModel의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인자에 따라 Qwen3 Omni Moe 모델을 인스턴스화하고 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 인스턴스화하면 Qwen/Qwen3-Omni-30B-A3B-Instruct와 유사한 설정이 생성됩니다.

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

Qwen3OmniMoeForConditionalGeneration

클래스 transformers.Qwen3OmniMoeForConditionalGeneration

< >

( config: Qwen3OmniMoeConfig )

Qwen3OmniMoeThinkerTextModel

클래스 transformers.Qwen3OmniMoeThinkerTextModel

< >

( config: Qwen3OmniMoeTextConfig )

매개변수

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

Qwen3OmniMoeThinker의 텍스트 부분이며, DeepStack이 시각적 특징을 초기 hidden state에 통합하기 때문에 순수 텍스트 전용 모델은 아닙니다.

이 모델은 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] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = Nonevisual_pos_masks: typing.Optional[torch.Tensor] = Nonedeepstack_visual_embeds: list[torch.Tensor] | None = None**kwargs: *<class 'transformers.modeling_flash_attention_utils.FlashAttentionKwargs'> ) → 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란 무엇인가요?

  • 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 인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다.
  • use_cache (bool, 선택 사항) — True로 설정하면 past_key_values 키 값 상태가 반환되며, 디코딩 속도를 높이는 데 사용할 수 있습니다( past_key_values 참조).
  • visual_pos_masks (torch.Tensor, shape (batch_size, seqlen), 선택 사항) — 시각적 위치의 마스크입니다.
  • deepstack_visual_embeds (list[torch.Tensor], 선택 사항) — Deepstack 시각 임베딩입니다. shape은 (num_layers, visual_seqlen, embed_dim)입니다. 이 특징은 서로 다른 시각 인코더 레이어에서 추출되어 디코더의 hidden states에 전달됩니다. DeepStack(https://arxiv.org/abs/2406.04334) 논문에서 가져온 것입니다.

반환값

MoeModelOutputWithPast 또는 tuple(torch.Tensor)

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

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

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

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

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

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

  • 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)을 계산하는 데 사용됩니다.

Qwen3OmniMoeThinkerModel

클래스 transformers.Qwen3OmniMoeThinkerModel

< >

( config: Qwen3OmniMoeThinkerConfig )

매개변수

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

오디오 백본과 언어 모델로 구성된 Qwen2.5OmniThinker 모델

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

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

forward

< >

( input_ids = Noneinput_features = Nonepixel_values = Nonepixel_values_videos = Noneimage_grid_thw = Nonevideo_grid_thw = Noneattention_mask = Nonefeature_attention_mask = Noneaudio_feature_lengths = Noneposition_ids = Nonepast_key_values = Noneinputs_embeds = Noneuse_cache = Noneoutput_router_logits: bool | None = Noneuse_audio_in_video = Nonevideo_second_per_grid = Nonemm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs ) → MoeModelOutputWithPast or tuple(torch.Tensor)

매개변수

  • input_ids (`of shape(batch_size, sequence_length)`) — 어휘 사전에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.

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

    입력 ID란 무엇인가요?

  • input_features (`of shape(batch_size, sequence_length, feature_dim)`) — 입력 오디오 특징에 해당하는 텐서입니다. 오디오 특징은 WhisperFeatureExtractor를 사용하여 얻을 수 있습니다. 자세한 내용은 WhisperFeatureExtractor.call()를 참조하세요 (Qwen3OmniMoeProcessor는 오디오 처리에 WhisperFeatureExtractor를 사용합니다).
  • pixel_values (`of shape(batch_size, num_channels, image_size, image_size)`) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 Qwen2VLImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 Qwen2VLImageProcessor.call()를 참조하세요 (Qwen3OmniMoeProcessor는 이미지 처리에 Qwen2VLImageProcessor를 사용합니다).
  • pixel_values_videos (`of shape(batch_size, num_frames, num_channels, frame_size, frame_size)`) — 입력 비디오에 해당하는 텐서입니다. 비디오의 픽셀 값은 Qwen2VLVideoProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 Qwen2VLVideoProcessor.call()를 참조하세요 (Qwen3OmniMoeProcessor는 비디오 처리에 Qwen2VLVideoProcessor를 사용합니다).
  • image_grid_thw (`of shape(num_images, 3)`) — LLM에서 각 이미지의 feature shape에 대한 시간, 높이, 너비입니다.
  • video_grid_thw (`of shape(num_videos, 3)`) — LLM에서 각 비디오의 특징 형식의 시간, 높이, 너비입니다.
  • attention_mask (`of shape(batch_size, sequence_length) -- Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]`:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

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

  • feature_attention_mask (torch.Tensor 형상이 (batch_size, feature_sequence_length), 선택 사항) — 패딩된 feature 인덱스에 attention을 수행하지 않도록 하는 마스크. 선택 가능한 마스크 값은 [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0
  • audio_feature_lengths (torch.LongTensor, shape (num_audios), 선택 사항) — LLM에서 각 오디오의 feature shape 길이입니다.
  • position_ids (`of shape(batch_size, sequence_length)) -- Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.n_positions - 1]`.

    포지션 ID란 무엇인가요?

  • past_key_values (`) -- Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the past_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.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 (`of shape(batch_size, sequence_length, hidden_size)) -- Optionally, instead of passing input_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_ids` indices into associated vectors than the model’s internal embedding lookup matrix.
  • use_cache (`) -- If set to True, past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values`).
  • output_router_logits (bool, 선택) — 모든 라우터의 logits를 반환할지 여부입니다. 라우터 손실을 계산하는 데 유용하며, 추론 단계에서는 반환하지 않아야 합니다.
  • use_audio_in_video (bool, 선택 사항) — 비디오에서 오디오 트랙을 사용할지 여부입니다. process_audio_info의 매개변수와 동일해야 합니다.
  • video_second_per_grid (torch.LongTensor, shape (num_videos), 선택 사항) — 각 비디오의 그리드당 초 수로, 시간적 특징 매핑에 사용됩니다.
  • mm_encoder_outputs (dict[str, ~modeling_outputs.BaseModelOutputWithPooling], 선택 사항) — 키가 지원되는 모달리티이고 값이 해당 모달리티의 인코딩된 출력인 딕셔너리입니다. 각 인코딩된 출력은 (pooler_output, 선택 사항: last_hidden_states, 선택 사항: hidden_states, 선택 사항: attentions) pooler_output의 형태가 (batch_size, sequence_length, hidden_size)인 선택 사항)으로 구성된 튜플이며, 인코더의 멀티모달 특징을 텍스트 임베딩에 병합한 시퀀스입니다.

반환값

MoeModelOutputWithPast 또는 tuple(torch.Tensor)

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

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

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

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

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

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

  • 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)을 계산하는 데 사용됩니다.

Qwen3OmniMoeThinkerForConditionalGeneration

클래스 transformers.Qwen3OmniMoeThinkerForConditionalGeneration

< >

( config: Qwen3OmniMoeThinkerConfig )

forward

< >

( input_ids = Noneinput_features = Nonepixel_values = Nonepixel_values_videos = Noneimage_grid_thw = Nonevideo_grid_thw = Noneattention_mask = Nonefeature_attention_mask = Noneaudio_feature_lengths = Noneposition_ids = Nonepast_key_values = Noneinputs_embeds = Nonelabels = Noneuse_cache = Noneoutput_router_logits: bool | None = Noneuse_audio_in_video = Nonevideo_second_per_grid = Nonemm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs ) → MoeCausalLMOutputWithPast or tuple(torch.Tensor)

매개변수

  • input_ids (`of shape(batch_size, sequence_length)`) — 어휘 사전에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.

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

    입력 ID란 무엇인가요?

  • input_features (`of shape(batch_size, sequence_length, feature_dim)`) — 입력 오디오 특징에 해당하는 텐서입니다. 오디오 특징은 WhisperFeatureExtractor를 사용하여 얻을 수 있습니다. 자세한 내용은 WhisperFeatureExtractor.call()를 참조하세요 (Qwen3OmniMoeProcessor는 오디오 처리에 WhisperFeatureExtractor를 사용합니다).
  • pixel_values (`of shape(batch_size, num_channels, image_size, image_size)`) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 Qwen2VLImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 Qwen2VLImageProcessor.call()를 참조하세요 (Qwen3OmniMoeProcessor는 이미지 처리에 Qwen2VLImageProcessor를 사용합니다).
  • pixel_values_videos (`of shape(batch_size, num_frames, num_channels, frame_size, frame_size)`) — 입력 비디오에 해당하는 텐서입니다. 비디오의 픽셀 값은 Qwen2VLVideoProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 Qwen2VLVideoProcessor.call()를 참조하세요 (Qwen3OmniMoeProcessor는 비디오 처리에 Qwen2VLVideoProcessor를 사용합니다).
  • image_grid_thw (`of shape(num_images, 3)`) — LLM에서 각 이미지의 feature shape에 대한 시간, 높이, 너비입니다.
  • video_grid_thw (`of shape(num_videos, 3)`) — LLM에서 각 비디오의 특징 형식의 시간, 높이, 너비입니다.
  • attention_mask (`of shape(batch_size, sequence_length) -- Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]`:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

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

  • feature_attention_mask (torch.Tensor 형상이 (batch_size, feature_sequence_length), 선택 사항) — 패딩된 feature 인덱스에 attention을 수행하지 않도록 하는 마스크. 선택 가능한 마스크 값은 [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0
  • audio_feature_lengths (torch.LongTensor, shape (num_audios), 선택 사항) — LLM에서 각 오디오의 feature shape 길이입니다.
  • position_ids (`of shape(batch_size, sequence_length)) -- Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.n_positions - 1]`.

    포지션 ID란 무엇인가요?

  • past_key_values (`) -- Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the past_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.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 (`of shape(batch_size, sequence_length, hidden_size)) -- Optionally, instead of passing input_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_ids` indices into associated vectors than the model’s internal embedding lookup matrix.
  • labels (`of shape(batch_size, sequence_length)) -- Labels for computing the masked language modeling loss. Indices should either be in [0, …, config.vocab_size]or -100 (seeinput_idsdocstring). Tokens with indices set to-100are ignored (masked), the loss is only computed for the tokens with labels in[0, …, config.vocab_size]`.
  • use_cache (`) -- If set to True, past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values`).
  • output_router_logits (bool, 선택) — 모든 라우터의 logits를 반환할지 여부입니다. 라우터 손실을 계산하는 데 유용하며, 추론 단계에서는 반환하지 않아야 합니다.
  • use_audio_in_video (bool, 선택 사항) — 비디오에서 오디오 트랙을 사용할지 여부입니다. process_audio_info의 매개변수와 동일해야 합니다.
  • video_second_per_grid (torch.LongTensor, shape (num_videos), 선택 사항) — 각 비디오의 그리드당 초 수로, 시간적 특징 매핑에 사용됩니다.
  • mm_encoder_outputs (dict[str, ~modeling_outputs.BaseModelOutputWithPooling], 선택 사항) — 키가 지원되는 모달리티이고 값이 해당 모달리티의 인코딩된 출력인 딕셔너리입니다. 각 인코딩된 출력은 (pooler_output, 선택 사항: last_hidden_states, 선택 사항: hidden_states, 선택 사항: attentions) pooler_output의 형태가 (batch_size, sequence_length, hidden_size)인 선택 사항)으로 구성된 튜플이며, 인코더의 멀티모달 특징을 텍스트 임베딩에 병합한 시퀀스입니다.

반환값

MoeCausalLMOutputWithPast 또는 tuple(torch.Tensor)

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

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

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

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

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

  • aux_loss (torch.Tensor, 선택 사항, output_router_logits=True가 전달되거나 config.output_router_logits=True인 경우, 그리고 모델이 로드 밸런싱 손실로 라우터를 학습하는 경우 반환됨) — 희소 모듈에 대한 로드 밸런싱 보조 손실입니다. 대신 라우터 바이어스로 전문가를 균형 맞추는 모델(DeepSeek-V3 및 이를 기반으로 파생된 아키텍처)은 router_logits를 반환하되 여기서는 None을 반환합니다.

  • router_logits (tuple(torch.Tensor), 선택 사항, output_router_logits=True가 전달되거나 config.output_router_logits=True인 경우 반환됨) — torch.Tensor의 튜플(스파스 레이어마다 하나)로, 형태는 (batch_size * sequence_length, num_experts)입니다.

    MoE 라우터가 계산한 원시 라우터 로짓입니다. 로드 밸런싱 손실을 계산하거나 토큰이 전문가로 어떻게 분배되는지 확인하는 데 사용할 수 있습니다.

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

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

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

예:

>>> from transformers import Qwen3OmniMoeProcessor, Qwen3OmniMoeThinkerForConditionalGeneration

>>> thinker = Qwen3OmniMoeThinkerForConditionalGeneration.from_pretrained("Qwen/Qwen2.5-Omni-7B")
>>> processor = Qwen3OmniMoeProcessor.from_pretrained("Qwen/Qwen2.5-Omni-7B")

>>> conversations = [
>>>         {'role': 'system', 'content': 'You are a helpful voice chat bot, and please respond to me in a casual conversation manner using random voice.'},
>>>         {"role": "user", "content": [
>>>             {"type": "image", "image": "https://www.ilankelman.org/stopsigns/australia.jpg"},
>>>             {"type": "audio", "audio": "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/audio/glass_breaking.mp3"},
>>>         ]},
>>> ]

>>> inputs = processor.apply_chat_template(
    conversations,
    tokenize=True,
    add_generation_prompt=True,
    return_dict=True,
    return_tensors="pt"
)

>>> # Generate
>>> generation = thinker.generate(**inputs, max_new_tokens=2048)
>>> generate_ids = generation[:, inputs.input_ids.size(1):]

>>> response = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]

get_audio_features

< >

( input_features: Tensorfeature_attention_mask: typing.Optional[torch.LongTensor] = Noneaudio_feature_lengths: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

매개변수

  • input_features (torch.Tensor) — 입력 오디오에 해당하는 텐서입니다.
  • feature_attention_mask (torch.LongTensor, 선택 사항) — 패딩된 feature 인덱스에 attention을 수행하지 않도록 방지하는 마스크입니다. [0, 1]에서 선택된 마스크 값:
  • audio_feature_lengths (torch.LongTensor, shape (num_audios), 선택 사항) — LLM에서 각 오디오의 feature shape 길이입니다.

반환값

BaseModelOutputWithPooling 또는 tuple(torch.Tensor)

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

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

예:

>>> from PIL import Image
>>> from transformers import AutoProcessor, Qwen3OmniMoeThinkerForConditionalGeneration

>>> model = Qwen3OmniMoeThinkerForConditionalGeneration.from_pretrained("Qwen/Qwen3-Omni-30B-A3B-Instruct")
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen3-Omni-30B-A3B-Instruct")

>>> 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

< >

( pixel_values: Tensorimage_grid_thw: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithDeepstackFeatures or tuple(torch.Tensor)

매개변수

  • pixel_values (torch.Tensor, shape (batch_size, num_channels, image_size, image_size)) — 입력 이미지에 해당하는 텐서입니다.
  • image_grid_thw (torch.LongTensor, shape (num_images, 3), 선택 사항) — LLM에서 각 이미지의 feature shape에 대한 시간, 높이, 너비입니다.

반환값

BaseModelOutputWithDeepstackFeatures 또는 tuple(torch.Tensor)

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

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

  • deepstack_features (List[torch.Tensor], 선택 사항) — deepstack 레이어의 hidden-states(피처 맵) 목록.

예:

>>> from PIL import Image
>>> from transformers import AutoProcessor, Qwen3OmniMoeThinkerForConditionalGeneration

>>> model = Qwen3OmniMoeThinkerForConditionalGeneration.from_pretrained("Qwen/Qwen3-Omni-30B-A3B-Instruct")
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen3-Omni-30B-A3B-Instruct")

>>> 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_video_features

< >

( pixel_values_videos: Tensorvideo_grid_thw: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithDeepstackFeatures or tuple(torch.Tensor)

매개변수

  • pixel_values_videos (torch.Tensor, shape (batch_size, num_channels, image_size, image_size)) — 입력 비디오에 해당하는 텐서입니다.
  • video_grid_thw (torch.LongTensor, shape (num_videos, 3), 선택 사항) — LLM에서 각 비디오의 feature shape에 해당하는 시간, 높이, 너비입니다.

반환값

BaseModelOutputWithDeepstackFeatures 또는 tuple(torch.Tensor)

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

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

  • deepstack_features (List[torch.Tensor], 선택 사항) — deepstack 레이어의 hidden-states(피처 맵) 목록.

예:

>>> from PIL import Image
>>> from transformers import AutoProcessor, Qwen3OmniMoeThinkerForConditionalGeneration

>>> model = Qwen3OmniMoeThinkerForConditionalGeneration.from_pretrained("Qwen/Qwen3-Omni-30B-A3B-Instruct")
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen3-Omni-30B-A3B-Instruct")

>>> 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]

Qwen3OmniMoeTalkerForConditionalGeneration

클래스 transformers.Qwen3OmniMoeTalkerForConditionalGeneration

< >

( config: Qwen3OmniMoeTalkerConfig )

매개변수

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

다른 모달리티(예: 이미지-텍스트-투-텍스트 생성)에 조건부화된 토큰 생성을 위한 Qwen3 Omni Moe 모델.

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

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

forward

< >

( input_ids = Noneattention_mask = Noneuse_audio_in_video = Noneaudio_feature_lengths = Nonevideo_second_per_grid = Noneimage_grid_thw = Nonevideo_grid_thw = Noneposition_ids = Nonepast_key_values = Noneinputs_embeds = Nonelabels = Noneuse_cache = Noneoutput_router_logits = Noneresidual_codes = Nonetrailing_text_hidden = Nonetts_pad_embed = Nonegeneration_step = Nonetalker_input_ids = None**kwargs ) → MoeCausalLMOutputWithPast or tuple(torch.Tensor)

매개변수

  • input_ids (`of shape(batch_size, sequence_length)`) — 어휘 사전에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.

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

    입력 ID란 무엇인가요?

  • attention_mask (`of shape(batch_size, sequence_length) -- Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]`:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

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

  • use_audio_in_video (bool, 선택 사항) — True로 설정하면 비디오의 오디오를 사용합니다.
  • audio_feature_lengths (torch.LongTensor, shape (num_audios), 선택 사항) — LLM에서 각 오디오의 feature shape 길이입니다.
  • video_second_per_grid (torch.LongTensor, shape (num_videos), 선택 사항) — 각 비디오의 그리드당 초 수로, 시간적 특징 매핑에 사용됩니다.
  • image_grid_thw (`of shape(num_images, 3)`) — LLM에서 각 이미지의 feature shape에 대한 시간, 높이, 너비입니다.
  • video_grid_thw (`of shape(num_videos, 3)`) — LLM에서 각 비디오의 특징 형식의 시간, 높이, 너비입니다.
  • position_ids (`of shape(batch_size, sequence_length)) -- Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.n_positions - 1]`.

    포지션 ID란 무엇인가요?

  • past_key_values (`) -- Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the past_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.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 (`of shape(batch_size, sequence_length, hidden_size)) -- Optionally, instead of passing input_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_ids` indices into associated vectors than the model’s internal embedding lookup matrix.
  • labels (`of shape(batch_size, sequence_length)) -- Labels for computing the masked language modeling loss. Indices should either be in [0, …, config.vocab_size]or -100 (seeinput_idsdocstring). Tokens with indices set to-100are ignored (masked), the loss is only computed for the tokens with labels in[0, …, config.vocab_size]`.
  • use_cache (`) -- If set to True, past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values`).
  • output_router_logits (“) — 모든 라우터의 logits를 반환할지 여부입니다. router loss를 계산하는 데 유용하며, 추론 단계에서는 반환하지 않아야 합니다.
  • residual_codes (torch.Tensor) — 이전 단계에서 예측된 잔차 코드입니다.
  • trailing_text_hidden (torch.Tensor) — 첫 번째 토큰 이후 thinker의 텍스트 hidden states.
  • tts_pad_embed (torch.Tensor) — tts_pad_token_id의 임베딩 텐서입니다.
  • generation_step (int) — prefill 이후의 generation step으로, trailing_text_hidden과 동기화하는 데 사용됩니다.
  • talker_input_ids (torch.Tensor) — thinker에서 전달된 입력 id로, 3d RoPE를 계산하는 데 사용됩니다.

반환값

MoeCausalLMOutputWithPast 또는 tuple(torch.Tensor)

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

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

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

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

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

  • aux_loss (torch.Tensor, 선택 사항, output_router_logits=True가 전달되거나 config.output_router_logits=True인 경우, 그리고 모델이 로드 밸런싱 손실로 라우터를 학습하는 경우 반환됨) — 희소 모듈에 대한 로드 밸런싱 보조 손실입니다. 대신 라우터 바이어스로 전문가를 균형 맞추는 모델(DeepSeek-V3 및 이를 기반으로 파생된 아키텍처)은 router_logits를 반환하되 여기서는 None을 반환합니다.

  • router_logits (tuple(torch.Tensor), 선택 사항, output_router_logits=True가 전달되거나 config.output_router_logits=True인 경우 반환됨) — torch.Tensor의 튜플(스파스 레이어마다 하나)로, 형태는 (batch_size * sequence_length, num_experts)입니다.

    MoE 라우터가 계산한 원시 라우터 로짓입니다. 로드 밸런싱 손실을 계산하거나 토큰이 전문가로 어떻게 분배되는지 확인하는 데 사용할 수 있습니다.

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

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

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

Qwen3OmniMoePreTrainedModel

class transformers.Qwen3OmniMoePreTrainedModel

< >

( config: PreTrainedConfig*inputs**kwargs )

매개변수

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

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

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

Qwen3OmniMoePreTrainedModelForConditionalGeneration

클래스 transformers.Qwen3OmniMoePreTrainedModelForConditionalGeneration

< >

( config: PreTrainedConfig*inputs**kwargs )

get_chunked_index

< >

( token_indices: Tensortokens_per_chunk: intremove_index: int ) → list[tuple[int, int]]

매개변수

  • token_indices (torch.Tensor, shape (seq_len, )) — 토큰 인덱스 값의 단조 증가 목록.
  • t_ntoken_per_chunk (int) — chunk당 토큰 수(chunk size 임계값으로 사용됨).
  • remove_index (int) token_indices에서 청킹 전에 빼야 할 인덱스 id —

반환값

list[tuple[int, int]]

각 token_indices의 청크에 대한 시작(포함) 및 끝(제외) 인덱스를 나타내는 튜플 목록입니다.

토큰 값 범위에 따라 토큰 인덱스 목록을 청크로 나눕니다.

토큰 인덱스 목록을 입력으로 받아, 토큰 값이 t_ntoken_per_chunk의 연속된 범위에 해당하는 목록의 슬라이스를 나타내는 (시작, 끝) 인덱스 튜플 목록을 반환합니다.

예를 들어, t_ntoken_per_chunk가 1000인 경우, 이 함수는 다음과 같은 조건을 만족하도록 청크를 생성합니다:

  • 첫 번째 청크에는 1000보다 작은 토큰 값이 포함되어
  • 두 번째 청크에는 1000 이상이고 2000 미만인 값이 포함되며, 이어서 같은 방식으로 나뉩니다.

get_rope_index

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneimage_grid_thw: typing.Optional[torch.LongTensor] = Nonevideo_grid_thw: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneuse_audio_in_video: bool = Falseaudio_seqlens: typing.Optional[torch.LongTensor] = Nonesecond_per_grids: typing.Optional[torch.Tensor] = None )

매개변수

  • input_ids (torch.LongTensor, shape (batch_size, sequence_length)) — 어휘 사전에서 입력 시퀀스 토큰의 인덱스입니다. 패딩을 제공한 경우 기본적으로 무시됩니다.
  • image_grid_thw (torch.LongTensor, shape (num_images, 3), 선택 사항) — LLM에서 각 이미지의 feature shape에 대한 시간, 높이, 너비입니다.
  • video_grid_thw (torch.LongTensor, shape (num_videos, 3), 선택 사항) — LLM에서 각 비디오의 feature shape에 해당하는 시간, 높이, 너비입니다.
  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0
  • use_audio_in_video (bool, 선택 사항) — True로 설정하면 비디오의 오디오를 사용합니다.
  • audio_seqlens (torch.LongTensor, shape (num_audios), 선택 사항) — LLM에서 각 오디오의 feature shape 길이입니다.
  • second_per_grids (torch.LongTensor, shape (num_videos), 선택 사항) — 3D 위치 ID에서 시간 차원 각 그리드 간 시간 간격(초 단위).

LLM에서 이미지와 비디오의 시간, 높이, 폭을 기반으로 3D rope 인덱스를 계산합니다.

설명: 각 임베딩 시퀀스는 비전 임베딩과 텍스트 임베딩을 모두 포함하거나, 텍스트 임베딩만 포함합니다.

순수 텍스트 임베딩 시퀀스의 경우, 회전 위치 임베딩은 최신 LLM과 차이가 없습니다. 예: input_ids: [T T T T T], 여기서 T는 텍스트를 나타냅니다. temporal position_ids: [0, 1, 2, 3, 4] height position_ids: [0, 1, 2, 3, 4] width position_ids: [0, 1, 2, 3, 4]

비전 및 텍스트 임베딩 시퀀스에 대해, 비전 부분은 3D rotary position embedding을, 텍스트 부분은 1D rotary position embedding을 계산합니다. 예시: Temporal (Time): 3개의 패치로, 비디오의 시간상 서로 다른 세그먼트를 나타냅니다. Height: 2개의 패치로, 각 프레임을 수직으로 나눕니다. Width: 2개의 패치로, 각 프레임을 수평으로 나눕니다. 또한 몇 가지 중요한 파라미터가 있습니다: fps (Frames Per Second): 비디오의 프레임 레이트로, 1로 설정되어 있습니다. 이는 1초마다 1프레임이 처리됨을 의미합니다. tokens_per_second: 매우 중요한 파라미터입니다. 비디오의 1초 구간에 개념적으로 얼마나 많은 “time-steps” 또는 “temporal tokens”가 포함되는지를 결정합니다. 이 경우 초당 25개의 토큰이 있습니다. 따라서 비디오의 각 초는 25개의 개별 시간점으로 표현됩니다. 본질적으로 시간적 세분화(temporal granularity)를 정의합니다. temporal_patch_size: 하나의 temporal patch를 구성하는 프레임 수입니다. 여기서는 2프레임입니다. interval: temporal position ID의 스텝 크기로, tokens_per_second temporal_patch_size / fps로 계산됩니다. 이 경우 25 2 / 1 = 50입니다. 이는 각 temporal patch의 temporal position ID가 50의 차이를 가짐을 의미합니다. input_ids: [V V V V V V V V V V V V T T T T T], 여기서 V는 비전을 나타냅니다. vision temporal position_ids: [0, 0, 0, 0, 50, 50, 50, 50, 100, 100, 100, 100] vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1] vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1] text temporal position_ids: [101, 102, 103, 104, 105] text height position_ids: [101, 102, 103, 104, 105] text width position_ids: [101, 102, 103, 104, 105] 여기서 텍스트 시작 position_ids는 최대 vision position_ids에 1을 더한 값으로 계산합니다.

Qwen3OmniMoeTalkerModel

클래스 transformers.Qwen3OmniMoeTalkerModel

< >

( config: Qwen3OmniMoeTalkerTextConfig )

매개변수

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

Qwen3OmniMoe의 텍스트 부분이며, DeepStack이 시각적 특징을 초기 hidden state에 통합하기 때문에 순수 텍스트 전용 모델이 아닙니다.

이 모델은 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] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = Nonevisual_pos_masks: typing.Optional[torch.Tensor] = Nonedeepstack_visual_embeds: list[torch.Tensor] | None = None**kwargs: *<class 'transformers.modeling_flash_attention_utils.FlashAttentionKwargs'> ) → 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란 무엇인가요?

  • 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 인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다.
  • use_cache (bool, 선택 사항) — True로 설정하면 past_key_values 키 값 상태가 반환되며, 디코딩 속도를 높이는 데 사용할 수 있습니다( past_key_values 참조).
  • visual_pos_masks (torch.Tensor, shape (batch_size, seqlen), 선택 사항) — 시각적 위치의 마스크입니다.
  • deepstack_visual_embeds (list[torch.Tensor], 선택 사항) — Deepstack 시각 임베딩입니다. shape은 (num_layers, visual_seqlen, embed_dim)입니다. 이 특징은 서로 다른 시각 인코더 레이어에서 추출되어 디코더의 hidden states에 전달됩니다. DeepStack(https://arxiv.org/abs/2406.04334) 논문에서 가져온 것입니다.

반환값

MoeModelOutputWithPast 또는 tuple(torch.Tensor)

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

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

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

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

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

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

  • 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)을 계산하는 데 사용됩니다.

Qwen3OmniMoeThinkerTextPreTrainedModel

class transformers.Qwen3OmniMoeThinkerTextPreTrainedModel

< >

( config: PreTrainedConfig*inputs**kwargs )

매개변수

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

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

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

Qwen3OmniMoeProcessor

클래스 transformers.Qwen3OmniMoeProcessor

< >

( image_processor = Nonevideo_processor = Nonefeature_extractor = Nonetokenizer = Nonechat_template = None )

매개변수

  • image_processor (Qwen2VLImageProcessor) — 이미지 프로세서가 필수 입력값입니다.
  • video_processor (Qwen2VLVideoProcessor) — video processor는 필수 입력값입니다.
  • feature_extractor (WhisperFeatureExtractor) — 피처 추출기는 필수 입력입니다.
  • tokenizer (Qwen2Tokenizer) — 토크나이저는 필수 입력값입니다.
  • chat_template (str) — 채팅의 메시지 목록을 토큰화 가능한 문자열로 변환하는 Jinja 템플릿입니다.

이미지 프로세서, 비디오 프로세서, 피처 추출기, 토크나이저를 단일 프로세서로 묶는 Qwen3OmniMoeProcessor를 생성합니다.

Qwen3OmniMoeProcessor는 Qwen2VLImageProcessor, Qwen2VLVideoProcessor, WhisperFeatureExtractor, Qwen2Tokenizer의 모든 기능을 제공합니다. 자세한 내용은 ~Qwen2VLImageProcessor, ~Qwen2VLVideoProcessor, ~WhisperFeatureExtractor, ~Qwen2Tokenizer를 참고하세요.

__call__

< >

( text: str | list[str] | list[list[str]] = Noneimages: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Nonevideos: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = Noneaudio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], NoneType] = None**kwargs: *<class 'transformers.models.qwen3_omni_moe.processing_qwen3_omni_moe.Qwen3OmniMoeProcessorKwargs'> ) → ~feature_extraction_utils.BatchFeature

매개변수

  • text (Union[str, list[str], list[list[str]]], 선택 사항) — 인코딩할 시퀀스 또는 시퀀스 배치입니다. 각 시퀀스는 문자열 또는 문자열 목록(사전 토큰화된 문자열)일 수 있습니다. 사전 토큰화된 입력을 전달하는 경우, 배치 입력과의 혼동을 피하기 위해 is_split_into_words=True를 설정하세요.
  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], 선택) — 전처리할 이미지입니다. 픽셀 값이 0에서 255 범위로 이루어진 단일 이미지 또는 배치 이미지를 기대합니다. 픽셀 값이 0에서 1 사이인 이미지를 전달하는 경우 do_rescale=False로 설정하세요.
  • videos (Union[list[PIL.Image.Image], numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], list[list[PIL.Image.Image]], list[list[numpy.ndarray]], list[list[torch.Tensor]], ~video_utils.URL, list[~video_utils.URL], list[list[~video_utils.URL]], ~video_utils.Path, list[~video_utils.Path], list[list[~video_utils.Path]]], 선택) — 전처리할 비디오입니다. 픽셀 값이 0에서 255 범위를 가지는 단일 비디오 또는 비디오 배치(batch)를 기대합니다. 픽셀 값이 0에서 1 범위를 가지는 비디오를 전달하는 경우 do_rescale=False로 설정하십시오.
  • audio (Union[numpy.ndarray, torch.Tensor, collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence[torch.Tensor]], 선택 사항) — 준비할 오디오 또는 오디오 배치입니다. 각 오디오는 NumPy 배열 또는 PyTorch 텐서일 수 있습니다. NumPy 배열/PyTorch 텐서의 경우, 각 오디오의 shape은 (C, T)여야 하며, 여기서 C는 채널 수, T는 오디오의 샘플 길이입니다.
  • min_pixels (int, kwargs, 선택) — 리사이즈 후 비디오 프레임의 최소 픽셀 수(높이 × 너비). 이 임계값보다 작은 프레임은 최소 요건을 충족하도록 업스케일링됩니다.
  • max_pixels (int, kwargs, 선택) — 리사이즈 후 비디오 프레임의 최대 픽셀 수(높이 × 너비). 이 임계값보다 큰 프레임은 제한 내에서 적합하도록 다운스케일링됩니다.
  • patch_size (int, kwargs, 선택 사항) — 비전 인코더가 사용하는 공간 패치 크기입니다. 비디오 프레임은 높이와 너비 차원에서 이 크기의 패치로 나뉩니다.
  • temporal_patch_size (int, kwargs, optional) — 비전 인코더가 사용하는 시간적 패치 크기입니다. 이는 몇 개의 연속된 프레임을 하나의 시간적 패치로 묶을지를 결정합니다.
  • merge_size (int, kwargs, 선택 사항) — 공간 패치를 결합하는 데 사용되는 병합 크기입니다. 여러 패치를 병합하여 공간 정보를 유지하면서 시퀀스 길이를 줄입니다.
  • min_frames (int, kwargs, optional) — 비디오에서 추출할 최소 프레임 수입니다. 이 수보다 적은 프레임을 가진 비디오는 이 요구 사항을 충족하도록 패딩되거나 반복됩니다.
  • max_frames (int, kwargs, 선택 사항) — 비디오에서 추출할 최대 프레임 수입니다. 이 한도를 초과하는 긴 비디오는 이 한도에 맞게 잘리거나 샘플링됩니다.
  • use_audio_in_video (bool, kwargs, 선택 사항, 기본값 False) — 비추천되는 인자입니다. 대신 load_audio_from_video를 사용하세요.
  • load_audio_from_video (bool, kwargs, 선택, 기본값 False) — 비디오를 처리할 때 오디오 정보를 포함할지 여부입니다. 활성화하면 시간적 정렬을 기반으로 오디오 토큰이 비디오 토큰과 교차 배치되어 통합된 멀티모달 표현이 생성됩니다.
  • seconds_per_chunk (float, kwargs, 선택 사항, 기본값 2.0) — 긴 비디오를 분할할 때 각 비디오 청크의 길이(초 단위)입니다. 이 매개변수는 처리를 위해 비디오를 시간적 세그먼트로 나누는 방식을 제어합니다.
  • position_id_per_seconds (int, kwargs 또는 float, 선택 사항, 기본값 25) — 1초의 비디오당 할당되는 position ID의 수입니다. 이 매개변수는 position embedding의 시간 해상도를 제어하며, use_audio_in_video=True일 때 비디오 토큰을 오디오 토큰과 정렬하는 데 사용됩니다.
  • return_tensors (str 또는 TensorType, 선택 사항) — 설정된 경우, 특정 프레임워크의 텐서를 반환합니다. 허용되는 값은 다음과 같습니다:
    • 'pt': PyTorch torch.Tensor 객체를 반환합니다.
    • 'np': NumPy np.ndarray 객체를 반환합니다.
  • **kwargs (ProcessingKwargs, 선택) — 각 모달리티(텍스트, 이미지, 비디오, 오디오)에 대한 추가 처리 옵션입니다. 모델별 매개변수는 위에 나열되어 있으며, 지원되는 인수의 전체 목록은 TypedDict 클래스를 참조하세요.

반환값

~feature_extraction_utils.BatchFeature

  • data (dict, 선택) — call/pad 메서드가 반환하는 리스트/배열/텐서 딕셔너리(‘input_values’, ‘attention_mask’ 등).
  • tensor_type (Union[None, str, TensorType], 선택 사항) — 초기화 시 PyTorch/Numpy 텐서에서 정수 목록을 변환하려면 여기에 tensor_type를 지정할 수 있습니다.
  • skip_tensor_conversion (list[str] 또는 set[str], 선택 사항) — tensor_type가 지정된 경우에도 텐서로 변환하지 않아야 하는 키의 목록 또는 집합.

Qwen3OmniMoeCode2Wav

클래스 transformers.Qwen3OmniMoeCode2Wav

< >

( config: Qwen3OmniMoeCode2WavConfig )

Qwen3OmniMoeCode2WavDecoderBlock

class transformers.Qwen3OmniMoeCode2WavDecoderBlock

< >

( config: Qwen3OmniMoeCode2WavConfiglayer_idx )

Qwen3OmniMoeCode2WavTransformerModel

클래스 transformers.Qwen3OmniMoeCode2WavTransformerModel

< >

( config: Qwen3OmniMoeCode2WavConfig )

매개변수

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

특정 헤드가 위에 없는 상태에서 원시 hidden-states를 출력하는 순수 Qwen3 Omni Moe 모델.

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

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

forward

< >

( input_ids = Noneattention_mask = Noneposition_ids = Nonepast_key_values = Noneinputs_embeds = Noneuse_cache = None**kwargs ) → BaseModelOutputWithPast or tuple(torch.Tensor)

매개변수

  • input_ids (`of shape(batch_size, sequence_length)`) — 어휘 사전에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.

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

    입력 ID란 무엇인가요?

  • attention_mask (`of shape(batch_size, sequence_length) -- Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]`:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

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

  • position_ids (`of shape(batch_size, sequence_length)) -- Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.n_positions - 1]`.

    포지션 ID란 무엇인가요?

  • past_key_values (`) -- Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the past_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.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 (`of shape(batch_size, sequence_length, hidden_size)) -- Optionally, instead of passing input_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_ids` indices into associated vectors than the model’s internal embedding lookup matrix.
  • use_cache (`) -- If set to True, past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values`).

반환값

BaseModelOutputWithPast 또는 tuple(torch.Tensor)

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

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

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

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

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

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

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

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

Qwen3OmniMoeTalkerCodePredictorModel

class transformers.Qwen3OmniMoeTalkerCodePredictorModel

< >

( config: Qwen3OmniMoeTalkerCodePredictorConfig )

매개변수

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

특정 헤드가 위에 없는 상태에서 원시 hidden-states를 출력하는 순수 Qwen3 Omni Moe 모델.

이 모델은 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] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPast 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란 무엇인가요?

  • 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 인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다.
  • use_cache (bool, 선택 사항) — True로 설정하면 past_key_values 키 값 상태가 반환되며, 디코딩 속도를 높이는 데 사용할 수 있습니다( past_key_values 참조).

반환값

BaseModelOutputWithPast 또는 tuple(torch.Tensor)

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

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

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

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

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

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

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

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

Qwen3OmniMoeTalkerCodePredictorModelForConditionalGeneration

클래스 transformers.Qwen3OmniMoeTalkerCodePredictorModelForConditionalGeneration

< >

( config: Qwen3OmniMoeTalkerCodePredictorConfig )

매개변수

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

다른 모달리티(예: 이미지-텍스트-투-텍스트 생성)에 조건부화된 토큰 생성을 위한 Qwen3 Omni Moe 모델.

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

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

forward

< >

( input_ids = Noneattention_mask = Noneposition_ids = Nonepast_key_values = Noneinputs_embeds = Nonelabels = Noneuse_cache = Nonegeneration_steps = None**kwargs ) → CausalLMOutputWithPast or tuple(torch.Tensor)

매개변수

  • input_ids (`of shape(batch_size, sequence_length)`) — 어휘 사전에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.

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

    입력 ID란 무엇인가요?

  • attention_mask (`of shape(batch_size, sequence_length) -- Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]`:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

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

  • position_ids (`of shape(batch_size, sequence_length)) -- Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.n_positions - 1]`.

    포지션 ID란 무엇인가요?

  • past_key_values (`) -- Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the past_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.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 (`of shape(batch_size, sequence_length, hidden_size)) -- Optionally, instead of passing input_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_ids` indices into associated vectors than the model’s internal embedding lookup matrix.
  • labels (`of shape(batch_size, sequence_length)) -- Labels for computing the masked language modeling loss. Indices should either be in [0, …, config.vocab_size]or -100 (seeinput_idsdocstring). Tokens with indices set to-100are ignored (masked), the loss is only computed for the tokens with labels in[0, …, config.vocab_size]`.
  • use_cache (`) -- If set to True, past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values`).
  • generation_steps (int) — 코드 예측기의 생성 단계, 0..num_code_groups-1

반환값

CausalLMOutputWithPast 또는 tuple(torch.Tensor)

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

Qwen3OmniMoeTalkerCodePredictorModelForConditionalGeneration의 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 (Cache, 선택 사항, use_cache=True가 전달되었거나 config.use_cache=True인 경우 반환됨) — Cache 인스턴스입니다. 자세한 내용은 kv cache 가이드를 참고하세요.

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

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

Update on GitHub