[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

KVキャッシュのオフロード戦略とGQAの実践的理解

KVキャッシュのオフロード戦略とGQAの実践的理解

こんにちは! LLM推論基盤プロビジョニング講座、今回は番外編をお届けします! 第3回「使用モデルの推論時消費メモリ見積もり」では、GPUメモリ消費の二大要素としてモデルのフットプリントとKVキャッシュを紹介し、1トークンあたりのKVキャッシュサイズの計算方法を解説しました。 また第4回「推論エンジンの選定」ではvLLMやDeepSpeedなど各推論エンジンの特性を比較し、第5回では量子化や並列化による最適化戦略を解説してきました。 しかし、実はKVキャッシュにはまだまだ掘り下げるべきトピックがあります。 * KVキャッシュをGPUのVRAMからCPU RAMやディスクにオフロードしたらどうなるのか? どのくらい遅くなるのか? * HuggingFace TransformersとvLLMでは、KVキャッシュの管理方針がなぜ根本的に異なるのか? * そもそもKVキャッシュが大きくなる原因であるアテンション構造を変えてしまう GQA(Grouped-Query Attention)とは何か? 第5回で紹介した量子化とは別の軸で、KVキャッシュを劇的に小さくする技術です。

By Qualiteg プロダクト開発部, Qualiteg コンサルティング
Python と JavaScript で絵文字の文字数が違う!サロゲートペアが引き起こす位置ずれバグの話

Python と JavaScript で絵文字の文字数が違う!サロゲートペアが引き起こす位置ずれバグの話

こんにちは! Qualitegプロダクト開発部です! PII(個人情報)検出のデモアプリを開発していて、検出したエンティティの位置をハイライト表示する機能を実装していました。 バックエンドは Python(FastAPI)、フロントエンドは JavaScript という構成です。 ある日、テストデータにこんなメール文面を使ったところ、ハイライトの位置が途中から微妙にずれるバグに遭遇しました。 鈴木一郎 様 いつもお世話になっております。 サンプル商事の佐藤でございます。 先日の件、確認が取れましたのでご連絡いたします。 お忙しいところ恐縮ですが、ご確認のほど宜しくお願い致します。 💻 #オンラインでのお打ち合わせ、お気軽に声がけください! ―――――――――――――――――――――――――――――― サンプル商事株式会社 営業部 第一課 山田 太郎 (Yamada Taro) 〒100-0001 東京都千代田区千代田1-1-1 サンプルビル 3F tel: 03-1234-5678 https://example.com/contact 検出結果をハイライト表示

By Qualiteg プロダクト開発部
大企業のAIセキュリティを支える基盤技術 - 今こそ理解するActive Directory 第5回 ブラウザ設定と認証

大企業のAIセキュリティを支える基盤技術 - 今こそ理解するActive Directory 第5回 ブラウザ設定と認証

こんにちは、今回はシリーズ第5回「ブラウザ設定と認証」について解説いたします! さて、前回(第4回)では、プロキシサーバーをドメインに参加させることで、ChatGPTやClaudeへのアクセスを「誰が」行ったかを確実に特定する仕組みを解説しました。「信頼の連鎖」の概念や、Windows版Squidなら1時間で構築できる環境、Negotiate/NTLM/Basicという3段階の認証フォールバック機構について理解いただけたかと思います。 しかし、せっかくサーバー側で完璧な統合Windows認証環境を構築しても、ブラウザ側の設定が適切でなければ、ユーザーには毎回パスワード入力ダイアログが表示されてしまいます。 「Edgeだと自動でログインできるのに、Chromeだとパスワードを聞かれる」 「同じサーバーなのにURLの書き方で動作が違う」 これらはヘルプデスクに寄せられる典型的な問い合わせです。(ただ、業務に好きなブラウザ使っていいよ、という企業はそんなに多くはないとおもいます) 今回は、統合Windows認証がブラウザでどのように動作するのか、その仕組みから各ブラウザ(Edge/

By Qualiteg AIセキュリティチーム, Qualiteg コンサルティング
スライドパズルを解くAIから学ぶ、「考える」の正体

スライドパズルを解くAIから学ぶ、「考える」の正体

こんにちは! 「このパズル、AIの教科書に載ってるらしいよ」 子供の頃に遊んだスライドパズル。いや、大人が遊んでも楽しいです。 数字のタイルをカチャカチャ動かして揃えるあれです。実はこのシンプルなパズルが、AI研究の出発点のひとつだったって知ってました? 今回は、このパズルを題材に「AIがどうやって考えているのか」を解き明かしていきます。しかも、ここで使われている手法は、Google Mapsの経路探索からChatGPTまで、現代の様々な技術のベースになっているんです。 まず遊んでみよう 理屈の前に、まずは感覚を思い出してみてください。 最初に shuffle をクリックすると、配置がシャッフルされゲームを開始できます。 ちなみに必ず解くことができるようになっていますが、慣れていないとそれなりに難しいかもしれません。 どうでしょう? 何手でクリアできましたか? クリアできなくても大丈夫です。記事後半で、実際にAIが解いてくれる機能つきゲームも掲載しています^^ 以下は動画です。本ブログで紹介するアルゴリズムで実際にパズルを解く様子をご覧いただけます

By Qualiteg 研究部