Upgrade to PRO for Only $50/Year—Limited-Time Offer! 🔥

Qwen3-VL入門:推論・物体検出・SFTまで

Avatar for bekku_zer bekku_zer
December 22, 2025
770

 Qwen3-VL入門:推論・物体検出・SFTまで

内輪のVLM勉強会で共有した内容で、Qwen3-VLの推論からSFTまで!

Avatar for bekku_zer

bekku_zer

December 22, 2025
Tweet

Transcript

  1. Qwen3の基本的な処理の流れ Qwen3-VLの紹介 ① Vision Encoderで、画像をtoken化 ② 画像tokenとテキストtokenを結合して、Qwen3 LMに入力する(interleave可) ③ Qwen3

    LM推論時にVision Encoderの特徴をQwen3 LMの最初の3層に追加する ④ Qwen3 LMからテキストのtokenが出力される 5
  2. Qwen3のアーキテクチャ Qwen3-VLの紹介 Interleaved MRoPE DeepStack RoPE の回転位置埋め込み の周波数帯の偏りを解消 し、時間・高さ・幅の位 置情報をembedding次元で

    均等に interleave。 ▶︎ 長コンテキスト (長動画)処理の性能を改善 Vision Encoder の複数層の 特徴量を LLM の複数層に 直接注入することで、 多階層特徴による視覚情 報を多角化 ▶︎ 画像や映像の小さい 文字に対する性能改善 Timestamp token 各 ビ デ オ の パ ッ チ に 対 し て、テキスト文字列として 表現される<hhhh:mm:ss>の ようなtokenを前置きして、 タイムスタンプを生成 ▶︎ 正確に動画に対する 時間情報を知覚できる 6
  3. Timestamp token[3] Qwen3-VLの紹介 特徴patchの前に、テキスト形式のTimestamp tokenを追加するだけ 9 [3] Chen, Shimin, et

    al. "Timemarker: A versatile video-llm for long and short video understanding with superior temporal localization ability." arXiv preprint arXiv:2411.18211 (2024).
  4. ① 教師あり微調整(SFT) ② 蒸留 ※教師モデル未知? ③ 強化学習  ・Reasoning Reinforcement Learning   

    ▶︎ thinking力を向上  ・General Reinforcement Learning    ▶︎ SFT後の問題を修正 (形式間違い、繰り返し癖、不正確表現) 学習の流れ Qwen3-VLの紹介 Pre-training Post-Training ① 視覚と言語のアライメント ②マルチモーダル事前学習 ③ 長コンテキスト事前学習 ④ 超長コンテキスト適応 10
  5. 性能結果 Qwen3-VLの紹介 Qwen3-VL-235B-A22B-Instructは、非推論モデルの中で多くの指標で Gemini 2.5 ProやGPT-5などのクローズドソースモデルを上回る 11 [4] Qwen3-VL: Sharper

    Vision, Deeper Thought, Broader Action(2025-12-22) https://qwen.ai/blog?id=b550154aa5ba6b812cdebba2b9dc1156c4369d40&from=research.research-list
  6. とりあえず、8Bで推論してみる Qwen3-VLで推論してみる unsloth/Qwen3-VL-8B-Instruct-unsloth-bnb-4bitで、推論 夕日が差し込む穏やかなビーチで、女性とラブラ ドールレトリバーが親しみながら座っています。 犬は前足を上げて女性の手に触れ、女性は笑顔で その姿に応えており、心温まる交流の瞬間を捉え ています。砂浜に広がる波の音と柔らかな光が、 心地よいひとときを演出しています。 このビデオは、Google

    Chromecastというデバイスを使って、スマートフォンやタブレットからテレビにコンテンツをストリーミングする様子を紹介してい ます。 はじめに、手がChromecastデバイスをテレビのHDMI端子に挿す様子が映し出されます。これは、Chromecastをテレビに接続して動画や音楽を再生するた めの準備段階です。次に、スマートフォンでYouTubeやNetflixなどのアプリを使ってコンテンツを閲覧している様子が映し出され、それをテレビで再生す る様子が示されます。このようにして、Chromecastを使えば、スマートフォンやタブレットの画面をテレビに投影することができます。 その後、3人の若者がソファに座って映画を楽しんでおり、画面に映る映画のシーンがそのままテレビに投影されていることがわかります。さらに、男の子 と女の子が一緒にテレビを見ている様子も映し出され、家族や友人たちと共有して楽しむことができるという点が強調されています。 最後に、Chromecastのロゴと公式サイトのURLが表示され、「google.com/chromecast」というテキストが映し出されます。これにより、視聴者がこの製 品の詳細や購入方法を確認することができるようになっています。 全体として、Chromecastは家庭で簡単に使いやすい、スマートフォンやタブレットのコンテンツをテレビに投影するための便利なデバイスであると強調さ れており、家族や友人たちと共有して楽しむことができる点が特に強調されています。また、製品の使い方やその利点について詳しく説明するためのビデ オであり、視聴者が製品の特徴やメリットを理解しやすくなっています。 1枚の画像 1分の動画 15
  7. 思考モデルで推論してみる Qwen3-VLで推論してみる Qwen3-VLは、“instruct”と“thinking”の2種類の異なるモデルとしてリリース unsloth/Qwen3-VL-8B-Thinking-bnb-4bitで、推論 1枚の画像 Okay, the user wants me

    to describe the image in Japanese. Let me look at the picture first. There's a woman sitting on the beach with a dog. The scene is during sunset, so the lighting is warm. The woman is wearing a plaid shirt and dark pants, and she's holding the dog's paw. The dog is a golden retriever or similar breed, sitting next to her, wearing a harness with colorful patterns. I need to make sure I capture all the details: the beach setting, the time of day (sunset), their interaction, the dog's harness, the woman's clothing, the ocean in the background. Also, the mood is peaceful and happy. The colors are soft with golden hues from the sunset. I should structure the description starting with the main subject, then the surroundings. Use appropriate Japanese terms for "sunset," "beach," "harness," etc. Check if there are any specific terms for the dog breed, but maybe just say "黄金色の犬" (golden dog). Also note the leash on the sand. Make sure the sentences flow well and are descriptive but not too wordy. Avoid using any English words; everything should be in Japanese. Wait, the user might be looking for a concise yet vivid description. Let me check the key elements: woman and dog on beach at sunset, interacting, warm light, ocean. Maybe mention the dog is sitting, woman is sitting cross-legged. The dog is wearing a colorful harness. They are touching paws, which shows a bond. The sand has footprints, ocean waves. Maybe include the time of day as "夕焼け" (sunset). I need to make sure all these points are covered in Japanese. Also, check for grammar and proper terms. Let me draft a few sentences: 夕焼けが美しい海辺の砂浜で、若い女性が座っています。彼女はチェック柄のシャツとダークカラーのパンツを着用し、黄金色の犬と一緒に座 っています。犬は首にカラフルなハーネスをつけており、女性はその前足を握り、楽しそうにしています。背景には青い海と波が見え、柔らかい光が二人を包ん でいます。砂は足跡で満ちており、温かみのある夕日が静かな時間を感じさせます。 Hmm, maybe "首にカラフルなハーネスをつけて" is correct. Check if "ハー ネス" is commonly used in Japanese, or if "首輪" is more common, but the dog is wearing a harness, so "ハーネス" should be okay. Also, "前足を握り" might be better as "前足を優しく握り" to emphasize the gentle action. Maybe the dog is standing up to shake paws with the woman? The image shows the dog sitting but with a front paw raised. The woman is holding the paw. So perhaps "犬は前足を上げ、女性が手を握っている" would be accurate. Let me adjust: イメージでは、犬 が座っている姿勢で前足を伸ばし、女性がその前足を握っている様子。Yes. So "犬は座って前足を伸ばし、女性がその手を握っており..." Also, check if the dog's harness is colorful. The harness has colorful patterns, so "カラフルな模様のハーネス". The woman is sitting cross-legged? The image shows her sitting on the sand with legs bent, so maybe "膝を折り" or "座り". The term "座っています" is okay. Make sure to mention the sunset creates a warm atmosphere, the sea in the background, footprints in the sand. Let me try again: 夕焼けの美しい砂浜で、若い女性とゴールデンレトリバーの犬が座っています。女性はチェック柄のシャツ を着用し、膝を立てて座り、犬の前足を握り合って笑顔です。犬はカラフルな模様のハーネスを着け、落ち着いた姿勢で向き合っています。背景には穏やかな海 が広がり、柔らかな夕日が砂の上に温かみを加えています。足跡が刻まれた砂浜は、この静かな時間が続くよう感じさせます。 Wait, the dog is a golden retriever, so "ゴールデンレトリバーの犬" or just "金色の犬" might be simpler. Also, check if "膝を立てて" is accurate. In the image, the woman is sitting with one leg bent under her. Maybe "片膝を立てて". Also, the dog is wearing a leash, which is on the sand next to them. So include "首にハーネスをつけており、首輪の他に赤い リードも砂の上に置かれている". Hmm, the leash is on the sand. So add that detail. Let me check again. The original image: the dog is sitting, wearing a harness, and the woman is sitting next to it, holding the dog's paw. There's a red leash on the sand. So revised: 砂浜で夕日が照らす中、若い女性と金色の犬が楽しそうに座 っています。女性はチェック柄のシャツと黒いパンツを着用し、片膝を立てて座り、犬の前足を握って微笑んでいます。犬はカラフルな模様のハーネスをつけて おり、赤いリードが砂の上に置かれています。背景には穏やかな波が打ち寄せ、柔らかな光が砂を金色に染め上げています。足跡が点々と残る砂浜は、この静か な一時をより一層豊かにしています。 Check for any errors. "片膝を立てて" is correct. "カラフルな模様のハーネス" for the colorful pattern harness. "赤いリードが 砂の上に置かれている" – the red leash is on the sand. "波が打ち寄せ" might be better as "波が打ち寄せる". Also, "金色の犬" is "golden dog", but maybe specify breed if it's clearly a golden retriever. The dog looks like a golden retriever, so "ゴールデンレトリバー" is accurate. Let me adjust that part: ゴールデンレトリバー の犬が、前足を上げて女性と手を握っています。 But in Japanese, it might be better to describe the action without specifying the breed, unless necessary. The image shows a golden retriever, but the user didn't specify the breed, so perhaps just "黄金色の犬". Final check: 夕焼けの砂浜で、若い女性と黄金色の犬が座って います。女性はチェック柄のシャツと黒いパンツを着用し、片膝を立てて座り、犬の前足を握って微笑んでいます。犬はカラフルな模様のハーネスをつけてお り、赤いリードが砂の上に置かれています。背景には穏やかな波が打ち寄せ、柔らかな光が砂を金色に照らし出しています。足跡が点々と残る砂浜には、二人が 静かに過ごす時間の温もりを感じさせます。 Wait, the woman is wearing a plaid shirt, so "チェック柄のシャツ" is correct. The dog has a harness with colorful patterns, so "カラフルな模様のハーネス". The leash is red, so "赤いリード". The sun is setting, so "夕焼け". The sea has gentle waves, "穏やかな波が打ち寄せ". The light is soft, making the sand golden. "砂を金色に照らし出しています". I think this covers all the key elements. Maybe include "両者は温かみのある関係にあり、幸 せな瞬間を共有しています" to describe their interaction. But the user asked for a description, not necessarily the emotion. So perhaps stick to the factual description but in a vivid way. Yes, the current version is good. Let me confirm once more: - Setting: beach at sunset - Woman: young, plaid shirt, dark pants, sitting cross-legged, holding dog's paw - Dog: golden color, harness with colors, sitting, raising front paw - Background: calm sea, soft light - Additional details: red leash on sand, footprints in sand, warm atmosphere All elements are included. The Japanese terms seem correct. Should be good. </think> 夕焼けが美しい砂浜で、若い女性とゴールデンレトリバー の犬が温かく向き合っています。女性はチェック柄のシャ ツと黒いパンツを着用し、片膝を立てて座り、犬の前足を 優しく握り、笑顔で話している様子です。犬はカラフルな 模様のハーネスを身につけ、前足を伸ばして人間と手をつ なぎ、穏やかな関係を築いています。彼らの周りには赤い リードが砂の上に置かれ、波が打ち寄せる青い海が背景に 広がっています。柔らかな夕日の光が砂を金色に照らし、 足跡が点々と残る砂浜には、静かな時間の温もりが感じら れます。遠くに見える夕焼けと海の景色が、心を穏やかに 包み込む、心温まる一瞬を切り取った一枚です。 <think>タブ内の思考 思考後の出力 16
  8. targets = ["person", "car", "dog"] instruction = f""" あなたは物体検出器です。 画像内から次の対象を検出し、

    各対象についてバウンディングボックスを返してください: {targets} 出力は必ずJSONのみ。 フォーマット: {{ "detections": [ {{ "label": "対象名", "score": 0.0, "bbox_1000": [x1, y1, x2, y2] }} ] }} 制約: - bbox_1000 は左上(x1,y1)・右下(x2,y2) - 座標は 0〜1000 の相対座標(整数) - score は 0〜1 - 返答に解説文やコードブロックは不要。JSONだけ出力してください。 """.strip() Bbox形式で出力して、物体検出してみる Qwen3-VLで推論してみる Bbox形式のフォーマットをプロンプトで指定することで、従来の物体検出が実現 1枚の画像 17 出てきた出力のjsonを抽出して、 Bboxとして表示
  9. Qwen3-VLの学習(SFT) from unsloth import FastVisionModel import torch model, tokenizer =

    FastVisionModel.from_pretrained( "unsloth/Qwen3-VL-8B-Instruct-unsloth-bnb-4bit", load_in_4bit = True, use_gradient_checkpointing = "unsloth", # True or "unsloth" for long context ) モデルのロード:from_pretrained unsloth/Qwen3-VL-8B-Instruct-unsloth-bnb-4bitから、 modelとtokenizerをロードする 20
  10. Loraを挿入モデル構築:get_peft_model Qwen3-VLの学習(SFT) get_peft_modelによって、学習対象のLoraを挿入したモデルを構築 # PEFTのモデルを構築 model = FastVisionModel.get_peft_model( model, finetune_vision_layers

    = True, finetune_language_layers = True, finetune_attention_modules = True, finetune_mlp_modules = True, r = 16, lora_alpha = 16, lora_dropout = 0, bias = "none", random_state = 3407, use_rslora = False, loftq_config = None, ) finetune_vision_layers=True ▶︎ 画像encoder側にLoraを挿入 finetune_language_layers=True ▶︎ 言語モデル側にLoraを挿入 finetune_attention_modules=True ▶︎ AttentionにもLoraを挿入 finetune_mlp_modules = True ▶︎ MLPFFNにもLoraを挿入 モデルの更新対象の範囲 Loraのハイパラ 21
  11. 入力データをモデルの入力形式(conversation)に変換 Qwen3-VLの学習(SFT) instruction = "Write the LaTeX representation for this

    image." def convert_to_conversation(sample): conversation = [ { "role": "user", "content" : [ {"type" : "text", "text" : instruction}, {"type" : "image", "image" : sample["image"]} ] }, { "role" : "assistant", "content" : [ {"type" : "text", "text" : sample["text"]} ] }, ] return { "messages" : conversation } converted_dataset = [convert_to_conversation(sample) for sample in dataset] 23
  12. SFTのTrainerを定義 Qwen3-VLの学習(SFT) Unsloth + TRL (SFTTrainer) を使って Vision-Language モデルの SFT(教師あり

    ファインチューニング) from unsloth.trainer import UnslothVisionDataCollator from trl import SFTTrainer, SFTConfig FastVisionModel.for_training(model) # Enable for training! trainer = SFTTrainer( model = model, tokenizer = tokenizer, data_collator = UnslothVisionDataCollator(model, tokenizer), # Must use! train_dataset = converted_dataset, args = SFTConfig( per_device_train_batch_size = 2, gradient_accumulation_steps = 4, warmup_steps = 5, max_steps = 30, # num_train_epochs = 1, # Set this instead of max_steps for full training runs learning_rate = 2e-4, logging_steps = 1, optim = "adamw_8bit", weight_decay = 0.001, lr_scheduler_type = "linear", seed = 3407, output_dir = "outputs", report_to = "none", # For Weights and Biases remove_unused_columns = False, dataset_text_field = "", dataset_kwargs = {"skip_prepare_dataset": True}, max_length = 2048, ), ) 【注意引数】 remove_unused_columns = False, ▶︎ Vision トレーニングには必須らしい dataset_text_field = “” ▶︎ 画像はtextを含まない場合もあるため、   事前設定必要 24
  13. 学習済みモデルで推論 Qwen3-VLの学習(SFT) 学習済みモデルに、Latexの数式画像 からLatex式を推論させる FastVisionModel.for_inference(model) # Enable for inference! image

    = dataset[2]["image"] instruction = "Write the LaTeX representation for this image." messages = [ {"role": "user", "content": [ {"type": "image"}, {"type": "text", "text": instruction} ]} ] input_text = tokenizer.apply_chat_template(messages, add_generation_prompt = True) inputs = tokenizer( image, input_text, add_special_tokens = False, return_tensors = "pt", ).to("cuda") from transformers import TextStreamer text_streamer = TextStreamer(tokenizer, skip_prompt = True) _ = model.generate(**inputs, streamer = text_streamer, max_new_tokens = 1024, use_cache = True, temperature = 1.5, min_p = 0.1) H ^ { \prime } = \beta N \int d \lambda \Big \{ { \frac { 1 } { 2 \beta ^ { 2 } N ^ { 2 } } } \partial _ { \lambda } \zeta ^ { \dagger } \partial _ { \lambda } \zeta + V ( \lambda ) \zeta ^ { \dagger } \zeta \Big \} \, . <|im_end|> 推論結果 26