[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

大企業のAIセキュリティを支える基盤技術 - 今こそ理解するActive Directory 第6回 よくある問題と解決方法

大企業のAIセキュリティを支える基盤技術 - 今こそ理解するActive Directory 第6回 よくある問題と解決方法

こんにちは、今回はシリーズ第6回トラブルシューティング - よくある問題と解決方法 について解説いたします! さて、前回(第5回)は、統合Windows認証がブラウザでどのように動作するかを解説しました。 「イントラネットゾーン」という概念を理解することで、同じサーバーでもURLの書き方(NetBIOS名、FQDN、IPアドレス)によって認証動作が変わる理由が明確になったかと思います。また、Chrome/Firefoxではデフォルトで統合認証が無効になっている理由と、グループポリシーによる一括設定方法も学びました。 しかし、設定が完璧なはずなのに「なぜかうまく動かない」という場面は、実際の現場では必ず訪れます。 「最近、ファイルサーバーへのアクセスが遅い」「金曜日は使えたのに、月曜日の朝にログインできない」「特定のサービスだけKerberosが失敗する」——これらはヘルプデスクに日々寄せられる典型的な問い合わせです。 原因はKerberosの失敗、時刻のずれ、SPNの設定ミス、DNS関連の問題など多岐にわたりますが、体系的にトラブルシューティングすることで必ず解決できます。

By Qualiteg コンサルティング, Qualiteg AIセキュリティチーム
AIエージェントを"事業に載せる"ために【第2回】AIエージェントの責任分解はなぜ難しいのか

AIエージェントを"事業に載せる"ために【第2回】AIエージェントの責任分解はなぜ難しいのか

— AI導入を"事業に載せる"ために、いま設計すべきこと(全3回) こんにちは!Qualitegコンサルティングチームです! 前回(第1回)では、Replit/Lemkin事件とDeloitte豪州政府報告書問題を通じて、AIエージェント導入の課題がモデル性能ではなく「権限・監査・責任の設計不在」にあることを見ました。 では、実際に事故が起きたとき、責任は誰が負うのでしょうか。第2回となる本記事では、法務・契約・組織の3つの観点から、AIエージェントの責任分解がなぜ難しいのかを構造的に整理します。 結論を先に言えば、法務だけでも契約だけでも組織論だけでも足りません。この3つを接続して設計しなければ、AIエージェントの責任分解は実務上機能しません。 1. 法的フレームワーク:複数の法理論が並走している AIエージェントが損害を出したとき、どの法理論で責任が問われるかについて、現時点でグローバルなコンセンサスは形成されていません。 Clifford Chanceの論考は、この状況の根本的な難しさを整理しています。法律は歴史的に、有害な行為がいつどのように発生したかを特定でき

By Qualiteg コンサルティング
AIエージェントを"事業に載せる"ために【第1回】

AIエージェントを"事業に載せる"ために【第1回】

AI導入事故は何を示しているのか — AI導入を"事業に載せる"ために、いま設計すべきこと(全3回) こんにちは!Qualitegコンサルティングチームです! AIエージェントを導入する企業が増える一方で、 「試してみる」段階から「事業に載せる」段階へ進める難しさ が、はっきり見え始めています。 本シリーズでは、AIエージェント導入を技術論だけでなく、責任分解・監査可能性・契約・運用統制を含む業務設計の問題として整理します。 全3回を通じて、「AIが賢いかどうか」ではなく、「AIを業務に載せるために何を設計するか」を考えていきます。 第1回となる本記事では、2025年に起きた2つの事例を出発点に、なぜいま「責任設計」が問題になっているのかを見ていきます。 上図は、本シリーズ全体で扱う論点の全体像です。 AIエージェントの導入は、技術的なモデル選定だけでは完結せず、権限設計、契約、監査、品質監視、保険、異常時対応まで含めた設計が必要になります。 第1回ではまず、なぜこうした設計が求められるようになったのかを、実際の事例から見ていきたいとおもいます なお、本シリー

By Qualiteg コンサルティング
PII検出の混同行列では見えないもの ― 認識器間衝突と統合テスト

PII検出の混同行列では見えないもの ― 認識器間衝突と統合テスト

こんにちは!Qualiteg研究部です! 個人情報(PII: Personally Identifiable Information)の自動検出は、テキスト中から特定の表現を抽出し、それがどの種類のPIIに当たるかを判定する問題として捉えることができます。 電話番号、人名、口座番号、金額表現など、検出対象のPIIタイプが増えるにつれて、単一の手法ではカバーしきれなくなり、性質の異なる複数の認識器(Recognizer)を組み合わせるマルチレイヤー構成が採用されるのが一般的です。 本稿で想定しているのは、ユーザーが海外製LLMにチャットを送信する直前に、その内容に個人情報や機密情報が含まれていないかをリアルタイムに検査するユースケースです。 この場面では、検出精度だけでなく、送信体験を損ねない速度が不可欠です。 高精度なLLMやBERT系モデル、NERベースの手法は有力ですが、送信前チェックの第一層として常時適用するには、レイテンシやコストの面で不利になることがあります。 そのため、本システムでは、正規表現、辞書、軽量なルールベース認識器を組み合わせた超高速な第一層を設け、そ

By Qualiteg 研究部, Qualiteg AIセキュリティチーム