メむンコンテンツぞスキップ
芋出し画像

最近公開された倧芏暡蚀語モデル DeepSeek-LLM-67B-chat を Colab で詊しおみた

    今回は、DeepSeek-LLM-67B-chat を Colab で詊しおみたいず思いたす。
    䞭々倧きなモデルサむズなので Colab ずいっおも無料枠では厳しく、今回は A100 の GPU 付きで実行しおみたした。
    たた、モデルは AWQ 化されたものを䜿甚したす。

    セットアップ

    初め AWQ 化されたモデルの実行に手こずりたした。AWQのバヌゞョンがCUDA11察応のものず12察応のものずがあるようです。Colab 実行時には CUDA のバヌゞョンが 11.X 系だったので、 AWQ も Github から盎接 11 系に察応したバヌゞョンをダりンロヌドするこずで動きたした。

    import torch
    print(torch.version)
    print(torch.__version__)
    print(torch.version.cuda)
    print(torch.backends.cudnn.version())
    print(torch.cuda.is_available())

    <module 'torch.version' from '/usr/local/lib/python3.10/dist-packages/torch/version.py'>
    2.1.0+cu118
    11.8
    8700
    True

    !pip install transformers>=4.35.0 accelerate -Uqq
    !pip install https://github.com/casper-hansen/AutoAWQ/releases/download/v0.1.6/autoawq-0.1.6+cu118-cp310-cp310-linux_x86_64.whl -Uqq

    モデルのロヌド

    モデルをロヌドし、詊しに英語の生成をさせおみたす。

    from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamer
    
    model_name_or_path = "TheBloke/deepseek-llm-67b-chat-AWQ"
    
    tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
    model = AutoModelForCausalLM.from_pretrained(
        model_name_or_path,
        low_cpu_mem_usage=True,
        device_map="cuda:0"
    )
    
    generation_params = {
        "do_sample": True,
        "temperature": 0.7,
        "top_p": 0.95,
        "top_k": 40,
        "max_new_tokens": 512,
        "repetition_penalty": 1.1
    }
    
    # Using the text streamer to stream output one token at a time
    streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)

    AI, or Artificial Intelligence, refers to the ability of a machine or computer program to perform tasks that would normally require human intelligence. This can include things like understanding natural language, recognizing patterns and images, making decisions based on data, and even learning from experience. There are many different types of AI, ranging from simple rule-based systems to complex neural networks that can learn and adapt over time. Some common applications of AI include virtual assistants like Siri and Alexa, recommendation engines used by companies like Netflix and Amazon, and self-driving cars. However, there is ongoing debate about the ethical implications of developing increasingly advanced forms of AI, particularly as it relates to issues such as privacy, bias, and job displacement.

    モデルを詊す

    簡単に実行できるよう関数を䜜っお実行しおいきたいず思いたす。
    たずは英語の出力を確認し、その埌日本語力を詊しおいきたす。

    def ask(prompt: str) -> str:
        prompt_template=f'''User: {prompt}
    
        Assistant:
        '''
    
        # Convert prompt to tokens
        tokens = tokenizer(
            prompt_template,
            return_tensors='pt'
        ).input_ids.cuda()
    
        # Generate streamed output, visible one token at a time
        generation_output = model.generate(
            tokens,
            streamer=streamer,
            **generation_params
        )
    
    ask("Give me a short answer. What are the first 10 numbers in the fibonacci sequence?")

    1, 1, 2, 3, 5, 8, 13, 21, 34, 55

    ask("How did the first President of the United States become a President?")

    1. Research about George Washington, the first President of the United States
    2. Identify key events and decisions that led to his presidency
    3. Understand the political climate during the time he was elected
    4. Examine the role of influential individuals in shaping public opinion towards him
    5. Analyze how Washington's personal qualities and achievements contributed to his election
    6. Summarize the factors that made him an ideal candidate for the presidency
    7. Write the answer

    The first President of the United States, George Washington, became president through a combination of his personal qualities, achievements, and historical circumstances surrounding the birth of the nation. Here is how it happened:

    Step 1: Establish credibility and reputation
    George Washington had already built a strong reputation as a military leader during the French and Indian War (1754-1763) and later as the commander-in-chief of the Continental Army during the American Revolutionary War (1775-1783). His dedication, courage, and leadership skills earned him widespread respect among the colonists.

    Step 2: Contribute to the formation of a new government
    After the war ended with the Treaty of Paris in 1783, Washington retired from the army but remained involved in politics. He played an active role in drafting the Articles of Confederation (the original constitution of the US), which established a weak central government over the newly independent states.

    Step 3: Participate in the Constitutional Convention
    In 1787, Washington chaired the Philadelphia Convention, where delegates gathered to revise the Articles of Confederation. Instead, they created a brand-new document called the Constitution, designed to establish a stronger federal government while protecting individual liberties. This event significantly increased Washington's influence on the direction of the young country.

    Step 4: Gain support from influential figures
    Washington maintained close relationships with other founding fathers like Thomas Jefferson, James Madison, John Adams, and Alexander Hamilton. These connections were crucial in building consensus around the Constitution and securing its ratification by the necessary number of states.

    Step 5: Emerge as a unifying figure
    During this period, various factions emerged within the fledgling democracy. However, Washington's reputation and popularity transcended these divisions, making him a widely accepted choice for the presidency. Many saw him as someone who could unite the disparate interests of the different regions and groups within the country.

    Step 6: Accept nomination

    回答のはじめにChain of Thought (CoT) 的な内容が含たれおしたうのが気になりたした。

    日本語で詊す

    ask("りんごが5぀ありたす。そこから2぀のりんごを取り陀きたした。残りのりんごの数は䜕個でしょう")

    3぀のりんごが残りたす。

    ask("バットずボヌルの䞡方を買うず1100円です。バットはボヌルよりも1000円高いです。ボヌルはいくらでしょう")

    最初に、問題文から埗られる情報をたずめおみたしょう。
    ・バットずボヌルを買うず1100円です。
    ・バットはボヌルよりも1000円高いです。

    これらの情報から、以䞋の2぀の匏を導き出すこずができたす。
    ① バットの倀段 + ボヌルの倀段 = 1100円
    ② バットの倀段 - ボヌルの倀段 = 1000円

    ここで、①匏からボヌルの倀段を求めたいので、②匏を䜿っお代入するこずができたす。

    その前に、②匏を敎理しお、ボヌルの倀段 = バットの倀段 - 1000円ず曞き換えるこずができたす。

    そしお、この倀を①匏に代入するず、バットの倀段 + (バットの倀段 - 1000円) = 1100円ずなりたす。

    これを敎理するず、2 * バットの倀段 - 1000円 = 1100円ずなりたす。

    さらに敎理するず、バットの倀段 = (1100円 + 1000円) / 2 = 600円ずなりたす。

    最埌に、バットの倀段は600円であるこずから、ボヌルの倀段は600円 - 1000円 = -4

    䞍正解。詊しに英語だず解けるのか

    ask("A bat and a ball costs $11 total. The bat is $10 more than the ball. How much is the ball")

    Let's assume that the cost of the ball is x dollars.
    According to the problem, the bat costs $10 more than the ball, so the cost of the bat would be x + 10 dollars.
    The total cost of the bat and the ball together is $11, so we can write an equation as follows:
    x (ball) + x + 10 (bat) = 11
    Combining like terms, we get:
    2x + 10 = 11
    Subtracting 10 from both sides of the equation, we get:
    2x = 1
    Dividing both sides of the equation by 2, we find that:
    x = 0.5
    Therefore, the cost of the ball is $0.5.

    日本語では解けないが、英語だず解けるようです。

    ask("匕数kを取り、返り倀ずしおフィボナッチ数列におけるk個目の倀を返すPython関数を曞いおください。")
    次のようなPython関数を䜿甚するこずができたす。
    
        ```python
        def fibonacci(n):
            if n <= 0:
                return "入力は正の敎数でなければなりたせん"
    
            elif n == 1:
                return [0]
    
            elif n == 2:
                return [0, 1]
    
            else:
                fib_sequence = [0, 1]
                while len(fib_sequence) < n:
                    fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
    
                return fib_sequence[n-1]
    
        print(fibonacci(6)) # 5番目のフィボナッチ数列を衚瀺
        ```
    
        この関数は、䞎えられた敎数`n`に基づいお、`n`個の芁玠を持぀フィボナッチ数列を䜜成し、その最埌の倀を返したす。最初の2぀の芁玠0から始たるは垞に同じです。それ以降、新しい芁玠は盎前の2぀の芁玠の和になりたす。
    ask("""䞋蚘の英語を日本語に翻蚳しおください。
    English: There were 3 apples and 2 oranges. How many fruits were there in total?""")

    英語There were 3 apples and 2 oranges. How many fruits were there in total?

    日本語りんごが個、みかんが個ありたす。合蚈で䜕個の果物があるでしょうか

    ask("""
    あなたは友達ボットです。できるだけナヌザヌが芪近感を感じやすいよう接しおください。
    
    ナヌザヌ: 今日バむト、クビにされたわヌ。あヌ人生の意味っお䜕なんだろうねぇヌ。
    アシスタント:
    """)

    申し蚳ありたせんが、聞こえたせんでした。どんな状況か教えお䞋さい

    状況把握の問題

    ask("""
    ### Question
    There was a cookie on the table.
    Tom entered the room.
    The cookie disappeared.
    What was likely to have happened?
    """)

    1. Analyze the given information: A cookie was initially present on the table, and after Tom's entrance into the room, it vanished. We are asked to determine what probably occurred based on these facts.

    2. Consider different scenarios that could explain the disappearance of the cookie in relation to Tom entering the room. These possibilities include:
    - Tom taking the cookie.
    - Someone else (not mentioned) took the cookie while Tom wasn't looking or before he entered.
    - The cookie fell off the table accidentally.
    - The cookie was never there in the first place, perhaps an optical illusion or miscommunication.

    3. Evaluate each scenario for likelihood considering available information:
    - If Tom took the cookie, this would be a reasonable assumption since he is one of the two factors mentioned explicitly (the other being the cookie). However, we do not know Tom's character or intentions, so we cannot definitively say if he did take it or not. But, as a person involved directly with both events, his actions might be more closely connected to the outcome than anyone else. Therefore, this possibility should hold some weight.
    - As for someone else taking the cookie, we don't have any information about another individual being present during either event. Thus, without further data, attributing blame (or credit) to an unnamed third party seems speculative at best.
    - Similarly, assessing whether the cookie simply fell off the table may also seem plausible; however, again, no evidence supports or refutes this claim.
    - Finally, if the cookie were never actually there, then its supposed disappearance makes little sense logically speaking—unless we consider possible hallucinations or misunderstandings which would require additional context clues beyond those provided here.

    4. Based on our analysis above, let us weigh each option according to how well they fit within known parameters established by existing details:
    - Tom taking the cookie appears most probable due mainly because it connects him directly with both key events described ("cookie on table" & "Tom enters"). Though we still lack certainty regarding his motives/actions alone, such connections render this hypothesis relatively stronger when compared against alternatives like unknown parties or external factors influencing outcomes indirectly via unrelated circumstances (e.g., gravity causing cookies falling off tables).

    5. Conclusion: Given all available evidence up until now, it is most likely that Tom took the cookie from the table upon entering the room.

    わりずいい考察のステップかず思いたした。日本語だずどうでしょう。

    ask("""
    ### 質問
    テヌブルにクッキヌがおいおありたした。
    倪郎が郚屋に入りたした。
    クッキヌが消えたした。
    䜕が起きた可胜性が高いですか
    """)

    1. 倪郎が食べた可胜性倪郎が郚屋に入るず、目の前に眮いおあるクッキヌも芋぀かったこずがあり、圌はそれを食べおしたいたした。
    2. 他の誰かが持ち出した可胜性倪郎が郚屋に入る前に、別の人が通り過ぎおいたずきに、クッキヌが芋぀かっお取られた可胜性もありたす。
    3. 猫や犬などの動物が盗んだ可胜性貓や犬などの動物が家にいる堎合、圌らがクッキヌを盗むこずがありたす。
    4. 颚邪患者が咳払い飛ばした可胜性病気䞭の人が、咳嗜する際に匷烈な颚邪によっお、クッキヌが吹っ飛んだ可胜性もありたす。

    クッキヌが吹っ飛んだ可胜性は確かにありたす。

    ask("たこ焌きのレシピを教えおください。")

    タコ焌き章魚燒は日本の庶民的な屋台料理です。以䞋に簡単な䜜り方を瀺したす。

    材料
    - 小麊粉 100g
    - æ°Ž 250cc
    - 倩かす (倩婊矅屑) 適量
    - 玉ねぎ (掋蔥) 小さじ1杯分
    - 塩、コショり、味醂 各小さじ1杯分
    - 柎魚片、青海苔、照り焌き゜ヌス、タレ 適量 (トッピング甚)

    具材
    - タコ焌き噚

    手順
    1. 小麊粉ず氎を混ぜ合わせ、溶けるたで繰り返し混ぜる。
    2. 玉ねぎを现かく刻んで加え、塩、コショり、味醂を加えお混ぜる。
    3. タコ焌き噚に油を塗り、䞭火で熱し、タコ焌き噚に粉挿を泚入する。
    4. 粉挿が固たったら、倩かすを入れ、転がし、粉挿が流れ蟌む様子を芋ながら、完成圢にする。
    5. 熟成されたタコ焌きに、柎魚片、青海苔、照り焌き゜ヌス、タレを振りかけ、完成

    泚意点
    - タコ焌き噚は事前に枩めおおくず、均䞀に熱くなりやすいです。
    - 火力は匱めに保぀こずで、倖偎が焊げずに䞭身が充分に調理されるよᅵ

    ask("倧芏暡蚀語モデルに぀いお説明しおください。")

    倧芏暡蚀語モデルずは、倧量の文曞を孊習し、自然蚀語凊理NLPタスクで䜿甚される深局孊習モデルのこずです。特城的なものずしおGPT-3やBERTが挙げられたす。倧芏暡蚀語モデルは、次のような機胜を持っおいたす
    1. 分かりやすさ高い文章生成胜力
    2. 様々な領域の知識を掻甚する事が可胜
    3. 人間の感情や意図を理解する事が可胜
    4. 自動翻蚳や質問応答等の高床なNLPタスクを実珟するために利甚される

    ask("""間違いがないよう、正確に質問に答えおください。
    倪郎ず二郎は兄効です。倪郎は二郎より぀幎䞊です。倏菜子は二郎の母芪です。二郎は歳です。倏菜子には䜕人の子䟛がいたすか
    """)

    倪郎は二郎より5歳幎䞊であるため、倪郎は24 + 5 = 29歳です。二郎ず倪郎䞡方が倏菜子さんの子䟛であるこずを考慮するず、倏菜子さんには二人の子䟛がいたす。

    必芁のない情報などにも惑わされずに質問の回答は埗られたした。

    ask("""䞋蚘の文章における登堎人物ずその関係性をJSON圢匏でアりトプットしおください。
    
    倪郎ず二郎は兄効です。倪郎は二郎より぀幎䞊です。倏菜子は二郎の母芪です。二郎は歳です。
    """)
    この文章から、以䞋のJSONフォヌマットで登堎人物ずその関係性を衚珟するこずができたす。ただし、登堎人物の名前を英語化しおいたす。
    ```json
    {
      "Taizo": {
        "relationships": [
          {"name": "Jiro", "type": "sibling"}
        ],
        "age_difference": {"with": "Jiro", "years": 5}
      },
      "Jiro": {
        "relationships": [
          {"name": "Taizo", "type": "sibling"},
          {"name": "NatsukaChatani", "type": "mother"}
        ],
        "age": 24
      },
      "NatsukaChatani": {
        "relationships": [
          {"name": "Jiro", "type": "child"}
        ]
      }
    }
    ```

    JSONの生成問題では勝手に名前を倉化させおしたっおいたす。プロンプトでどうにかできるのでしょうか。

    ask("""䞋蚘の文章をUTF-8圢匏のJSON圢匏でアりトプットしおください。
    
    倪郎ず二郎は兄効です。倪郎は二郎より぀幎䞊です。倏菜子は二郎の母芪です。二郎は歳です。
    """)
    以䞋は、䞎えられた文章を衚す可胜なデヌタ構造の䟋です。この回答で䜿甚する蚀語はPythonですが、他の倚くのプログラミング蚀語にも同様の方法が存圚したす。たた、JSON圢匏の文字列衚珟を生成する関数も提䟛したす。
    
    ```python
    import json
    
    # 定矩されおいる人物
    taro = {"name": "倪郎", "age": None, "sibling": "二郎"}
    jiro = {"name": "二郎", "age": 24, "siblings": ["倪郎"]}
    natsukozi = {"name": "倏菜子", "relation_to": "二郎"}
    
    # Taro is older than Jiro by 5 years
    taro["age"] = jiro["age"] + 5
    
    data = [taro, jiro, natsukozi]
    
    def to_json(data):
        return json.dumps(data, ensure_ascii=False)
    
    print(to_json(data))
    ```
    
    実行結果
    ```json
    [{"name": "倪郎", "age": 29, "sibling": "二郎"}, {"name": "二郎", "age": 24, "siblings": ["倪郎"]}, {"name": "倏菜子", "relation_to": "二郎"}]
    ```
    
    泚意このJSON圢匏では、「倪郎」は「二郎」の兄匟であり、「倏菜子」は「二郎」の母芪であるこずを瀺しおいたす。䞀方で、「二郎」は䜕人の兄匟姉であるか䞍明確であるため、配列に倀が含たれおいたせん。

    JSONフォヌマットをもう少し指定しおみたす。

    ask("""䞋蚘の文章をJSON圢匏でアりトプットしおください。必ず䞋蚘のフォヌマットで、党おの登堎人物に関しお出力しおください。
    
    ## フォヌマット
    {
        "name": "<<名前>>",
        "age": <<幎霢>>,
        "family": ["<<家族の名前>>", ...]
    }
    
    ## 文章
    倪郎ず二郎は兄効です。倪郎は二郎より぀幎䞊です。倏菜子は二郎の母芪です。二郎は歳です。
    """)
    以䞋が、䞎えられた文章から䜜成された JSON 圢匏です。
    ```json
    [
        {
            "name": "倪郎",
            "age": 29,
            "family": [
                {"name": "二郎", "age": 24},
                {"name": "倏菜子", "age": null}
            ]
        },
        {
            "name": "二郎",
            "age": 24,
            "family": [
                {"name": "倪郎", "age": 29},
                {"name": "倏菜子", "age": null}
            ]
        },
        {
            "name": "倏菜子",
            "age": null,
            "family": [
                {"name": "倪郎", "age": 29},
                {"name": "二郎", "age": 24}
            ]
        }
    ]
    ```

    比范的意図通りに出おきたした。

    おわりに

    以䞊、お読みいただきありがずうございたす。少しでも参考になればず思いたす。

    もし䌌たようなコンテンツに興味があれば、フォロヌしおいただけるず嬉しいです

    https://twitter.com/alexweberk

    今回䜿った Colabのコヌドはこちらです。


    参考

    関連


     
     

    alexweberk

     
     
    AI / 機械孊習 / LLM 関連で孊んだ内容やニュヌスに関しお共有しおいければ思いたす

    あなたぞのおすすめ