[ChatStream] Llama2 対応の ChatPrompt実装

[ChatStream] Llama2 対応の ChatPrompt実装

こんにちは! (株)Qualiteg プロダクト開発部 です!

本稿では、 ChatStream にLlama2 対応の ChatPrompt を同梱いたしましたのでご紹介いたします!

現在の ChatPrompt は以下とおりとなっております。旧バージョンのChatStreamをご利用の場合も、以下コードにて Llama2対応可能です。(もちろん最新バージョンのChatStreamには同梱済です)

from chatstream import AbstractChatPrompt
from chatstream.chat_prompt.role_type import RoleType

SYSTEM_PROMPT = """\
You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.\
"""


class ChatPromptMetaLlamaLlama2Chat(AbstractChatPrompt):
    """
    meta-llama/Llama-2-7b-chat

    Prompt Guide from
    https://huggingface.co/blog/llama2
    """

    def __init__(self):
        super().__init__()  # Call the initialization of the base class
        self.set_system(f"<s>[INST] <<SYS>>\n{SYSTEM_PROMPT}\n<</SYS>>\n\n")
        self.set_requester("")
        self.set_responder("")

    def get_stop_strs(self):
        if not self.chat_mode:
            return None
        return []

    def get_custom_skip_echo_len(self, skip_echo_len):
        # modify skip_echo_len when using llama2
        num_turn = self.get_turn()
        if num_turn >= 2:
            modified_skip_echo_len = skip_echo_len + 1 * self.get_turn()
            return modified_skip_echo_len
        return skip_echo_len

    def get_replacement_when_input(self):
        return None

    def get_replacement_when_output(self):  # replace when response_text gotten
        return None

    def create_prompt(self, opts={}):
        if self.chat_mode == False:
            return self.get_requester_last_msg()

        # Chat Mode == True の場合のプロンプトを構築する
        ret = self.system

        for chat_content in self.get_contents(opts):

            chat_content_role_type = chat_content.get_role_type()
            chat_content_message = chat_content.get_message()

            if chat_content_message:
                merged_message = ""
                if chat_content_role_type == RoleType.REQUESTER:
                    merged_message = f"{chat_content_message} [/INST] "
                elif chat_content_role_type == RoleType.RESPONDER:
                    merged_message = f"{chat_content_message} </s><s>[INST] "
                ret += merged_message
            else:
                pass

        return ret

    def build_initial_prompt(self, chat_prompt):
        # 初期プロンプトは実装しない
        pass


本実装については、1点だけトリッキーな実装を含んでいます。
というのも、ChatStreamはストリーミングチャットが基本ですので新たに生成された1トークン分を更新していくことでリアルタイムで流れるようなチャットを実現しています。そのため、出力が期待と1文字でもズレてしまうと、ストリーミング時に1文字かけたり、全体が1文字ずつズレてしまったりする現象が発生しやすいです。

Llama2の出力の場合、ターンごとに1文字ずつ出力に空白文字が発生する現象が確認されており、 なにがしかのSpecial Token や空トークン、またコード変換の影響を疑っていましたが根本原因の特定に至らず、現象をキャンセルするための実装を入れています。

現象としましては、

以下のプロンプトを入力プロンプトとしたとき、

<s>[INST] <<SYS>>
You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.
<</SYS>>

Do you know the movie titanic [/INST] Hello! Yes, I'm familiar with the movie Titanic. It's a classic film directed by James Cameron, released in 1997, and starring Leonardo DiCaprio and Kate Winslet. The movie is based on the true story of the RMS Titanic, a British passenger liner that sank in the North Atlantic Ocean in 1912 after colliding with an iceberg. The film follows the story of Jack Dawson (played by DiCaprio) and Rose DeWitt Bukater (played by Winslet), who come from </s><s>[INST] Who is the director [/INST] The director of the movie "Titanic" is James Cameron. </s><s>[INST] Who is starred [/INST] ]  The movie "Titanic" features a star-studded cast, including:
* Leonardo DiCaprio as Jack Dawson
* Kate Winslet as Rose DeWitt Bukater
* Billy Zane as Cal Hockley
* Kathy Bates as Molly Brown
* Frances Fisher as Ruth DeWitt Bukater
* Bernard Hill as Captain Edward John Smith
* Jonathan Hyde as J. Bruce Ismay
* Eric Braeden as John Jacob Astor IV
* Gloria Stuart as Old Rose

These actors brought the characters from the movie to life and </s><s>[INST] 

出力は以下のようになります

[INST] <<SYS>>
You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.
<</SYS>>

Do you know the movie titanic [/INST] Hello! Yes, I'm familiar with the movie Titanic. It's a classic film directed by James Cameron, released in 1997, and starring Leonardo DiCaprio and Kate Winslet. The movie is based on the true story of the RMS Titanic, a British passenger liner that sank in the North Atlantic Ocean in 1912 after colliding with an iceberg. The film follows the story of Jack Dawson (played by DiCaprio) and Rose DeWitt Bukater (played by Winslet), who come from  [INST] Who is the director [/INST] The director of the movie "Titanic" is James Cameron.  [INST] Who is starred [/INST]

Input:
Do you know the movie titanic [/INST] Hello! Yes, I'm familiar with the movie Titanic. It's a classic film directed by James Cameron, released in 1997, and starring Leonardo DiCaprio and Kate Winslet. The movie is based on the true story of the RMS Titanic, a British passenger liner that sank in the North Atlantic Ocean in 1912 after colliding with an iceberg. The film follows the story of Jack Dawson (played by DiCaprio) and Rose DeWitt Bukater (played by Winslet), who come from [INST] Who is the director [/INST] The director of the movie "Titanic" is James Cameron. [INST] Who is starred [/INST] 

つまり入力プロンプトが [INST] つまり 半角スペース1つ[INST] でも出力で、 [INST]半角スペース2つ + [INST] となって戻ってくるため、新規生成文章の切り出しで1レスポンスにたいして1文字ズレの発生が観測されます。

それならばと、入力プロンプトを 半角スペース2つ[INST] で入力したが、その場合は出力生成文は 半角スペース3つ[INST]
となり、ズレが解消されないようです。

このとき、通常のテキスト処理で trim していく方法もありますが、当ChatPromptではなるべくもとの入力と出力を変形しないことをポリシーとして、

    def get_custom_skip_echo_len(self, skip_echo_len):
        # modify skip_echo_len when using llama2
        num_turn = self.get_turn()
        if num_turn >= 2:
            modified_skip_echo_len = skip_echo_len + 1 * self.get_turn()
            return modified_skip_echo_len
        return skip_echo_len

のように、 skip_echo_len をターンにあわせて調整することでピッタリの切り出しに対応しました。約1000通りの入出力において、問題なく切り出せているため、本手法を workaround として採用しています。ちょっとした見落としの可能性も高そうなので根治のために研究部側で引き続き原因調査しています。

Llama2 をベースモデルとして採用しているほかモデルも同様の現象が発生していますが、本手法にて解決できました。

Read more

発話音声からリアルなリップシンクを生成する技術 第2回:AIを使ったドリフト補正

発話音声からリアルなリップシンクを生成する技術 第2回:AIを使ったドリフト補正

こんにちは! 前回の記事では、当社のMotionVoxで使用している「リップシンク」技術について、wav2vecを用いた音声特徴量抽出の仕組みを解説しました。音声から正確な口の動きを予測するための基礎技術について理解いただけたかと思います。 今回は、その続編として、リップシンク制作における重要な技術的課題である「累積ドリフト」に焦点を当てます。wav2vecで高精度な音素認識ができても、実際の動画制作では複数の音声セグメントを時系列に配置する際、わずかなタイミング誤差が蓄積して最終的に大きなずれとなる現象が発生します。 本記事では、この累積ドリフトのメカニズムと、機械学習を活用した最新の補正技術について、実際の測定データを交えながら詳しく解説していきます。前回のwav2vecによる特徴抽出と今回のドリフト補正技術を組み合わせることで、MotionVoxがどのように高品質なリップシンクを実現しているのか、その全体像が見えてくるはずです。 累積ドリフトとは何か 基本概念 累積ドリフトとは、個々の音声セグメントが持つ微小なタイミング誤差が、時間の経過とともに蓄積していく現象で

By Qualiteg 研究部
AIエージェント時代の新たな番人「ガーディアンエージェント」とは?

AIエージェント時代の新たな番人「ガーディアンエージェント」とは?

こんにちは!今日は先日ガートナーが発表したガーディアンエージェントについて解説します ガートナーの公式定義 ハイプカーブで有名なガートナーは2025年6月に、ガーディアンエージェントに関する見解を発表しました。ガーディアン・エージェントとは、AIとの安全で信頼できるやりとりを支援するために設計されたAIベースのテクノロジです。 ざっくりいうと、 「AIエージェントが来るよ」と予言したガートナー社は、次は、「ガーディアンエージェントが来るよ」と予言しました。なぜガーディアンエージェントが来るのでしょうか?本稿では、そのあたりを考察していきたいと思います。 なぜ今、AIの「監視役」が必要なのか 2025年、私たちは本格的なAIエージェント時代の入り口に立っています。AIが単なるツールから、自律的に判断し行動する「エージェント」へと進化する中で、新たな課題が浮上しています。 従来のAIとエージェント型AIの違い さて、ガーディアンエージェントが必要になる理由として、生成AI(以後AIと呼びます)の急速な進化があげられます。従来のAIとエージェント型AIの違いを思い出

By Qualiteg コンサルティング
LLM推論基盤プロビジョニング講座 第4回 推論エンジンの選定

LLM推論基盤プロビジョニング講座 第4回 推論エンジンの選定

こんにちは!前回までの講座では、LLMサービス構築に必要なリクエスト数の見積もりや、使用モデルの推論時消費メモリ計算について詳しく解説してきました。今回は7ステッププロセスの4番目、「推論エンジンの選定」について詳しく掘り下げていきます。 推論エンジンとは何か 推論エンジンとは、GPU上でLLMモデルの推論計算(テキスト生成)を効率的に行うために設計された専用のソフトウェアプログラムです。一般的なディープラーニングフレームワーク(PyTorch、TensorFlowなど)でも推論は可能ですが、実運用環境では専用の推論エンジンを使用することで、大幅なパフォーマンス向上とリソース効率化が期待できます。 推論エンジンは単なる実行環境ではなく、様々な最適化技術を実装しています。特定のモデルアーキテクチャに特化した最適化機能を実装したものや、推論速度の高速化に特化したもの、前回解説したKVキャッシュのメモリ効率化機能を備えたものなど、それぞれ特徴が異なります。そのため、自社で採用したLLMモデルや運用環境、要件に合致した推論エンジンを選定することが重要です。 推論エンジン選定のアプロ

By Qualiteg コンサルティング
発話音声からリアルなリップシンクを生成する技術 第1回:音素とwav2vec

発話音声からリアルなリップシンクを生成する技術 第1回:音素とwav2vec

こんにちは! 今日は当社のMotionVox でも実際に使っている「リップシンク」技術について総合的に解説してみたいとおもいます。 音声に合わせて自然な口の動きを生成するリップシンク技術は、AIアバターや3Dアニメーション制作においても重要な技術です。 本記事では、最新のディープラーニング技術を活用したリップシンク学習の基礎から実装まで、技術的な観点から詳しく解説します。 1. リップシンク学習の基礎概念 1.1 問題設定 リップシンク学習とは、音声データから対応する口の動きを予測する回帰問題ととらえることができます f: 音声特徴量(t) → 口の動きパラメータ(t) この問題のコアは 音韻(音の特徴)と視素(視覚的な口の形)の対応関係を学習する ことにあります。 1.2 音韻-視素マッピングの複雑性 ただし! 人間の発話における音と口の形の関係は、単純な1対1マッピングではないんです。 同じ音でも文脈で変化 「あ」の発音でも: - 「か」の後の「あ」→ 口がやや狭めから開く - 「ん」の後の「あ」→ 口が閉じた状態から大きく開く 調音結合

By Qualiteg 研究部, Qualiteg コンサルティング