01-ai/Yi-6B-ChatをGoogle Colabで動かしてみた

AI・機械学習

はじめに

最近トレンド入りしている「01-ai/Yi-34B」を動かしたかったのですが無料版Google Colabでは動かなかったため6Bにしました。


下記の記事もおすすめ

Youri-7b-chat-gptqをGoogleColabでちょっとだけ遠坂凛ぽく喋らせてみた
はじめに以下は、Google Colabで「youri-7b-chat-gptq」を使用して、「遠坂凛」のように話すAIを設定する手順のステップバイステップの解説です。Google Colabはオンラインで実行できるJupyterノートブッ...
Youri-7b-chat-gptqを使ったLinebotの構築
はじめにこちらの記事の続きですMessaging APIの使い方はこちらこのコードは、YouriBot というLINE Botを構築するためのPythonクラスを定義しています。このクラスは、LINE メッセージイベントを処理し、AIモデル...

ざっくりコード解説


# Pythonのパッケージ管理ツールpipを使って、bitsandbytesとaccelerateという2つのライブラリをインストールします。
# -qqqオプションでインストール中の出力を最小限にします。
!pip -qqq install bitsandbytes accelerate

# 必要なライブラリをインポートします。
import transformers
import accelerate

# accelerateとtransformersライブラリのバージョンを出力します。
print(accelerate.__version__)
print(transformers.__version__)

# transformersライブラリから必要なモジュールをインポートします。
from transformers import AutoModelForCausalLM, AutoTokenizer

# 事前に訓練された言語生成モデルとトークナイザをロードします。
model = AutoModelForCausalLM.from_pretrained("01-ai/Yi-6B-Chat", device_map="auto", torch_dtype="auto")
tokenizer = AutoTokenizer.from_pretrained("01-ai/Yi-34B")

# 入力テキストをトークナイズし、PyTorchテンソルに変換します。
inputs = tokenizer("There's a place where time stands still. A place of breath taking wonder, but also", return_tensors="pt")

# 生成するテキストの最大長を設定します。
max_length = 256

# モデルを使ってテキストを生成します。様々なパラメーターで生成プロセスを制御します。
outputs = model.generate(
    inputs.input_ids.cuda(),
    max_length=max_length,
    eos_token_id=tokenizer.eos_token_id,
    do_sample=True,
    repetition_penalty=1.3,
    no_repeat_ngram_size=5,
    temperature=0.7,
    top_k=40,
    top_p=0.8,
)

# 生成されたテキストをデコードし、出力します。
print(tokenizer.decode(outputs[0], skip_special_tokens=True))

出力


There's a place where time stands still. A place of breath taking wonder, but also one that can be the source of deep sorrow and grief for those who have lost their loved ones there. This is known as "The Field Of Lost Shoes" or simply The Shoe Tree.
Located in an area steeped with history on both sides of the border between Northern Ireland and County Donegal, this spot has become something more than just another natural landmark; it serves as a poignant memorial to all children whose lives were cut short during some of Europe’s darkest times—the Irish Potato Famine (1845-1852) which saw over 1 million people die from starvation alone due largely because they could no longer afford bread made out potatoes when these crops failed so miserably across much southern parts Britain & France too at around same period – leading eventually towards widespread famine conditions throughout many regions including Ulster region within modern day Republic oIreland today! It was here amongst rolling hillsides covered entirely by lush green grasses dotted w/wildflowers alongside bubbling brooks running clear freshwater streams beneath leafy trees providing shade against harsh sunrays overhead -that weary souls sought refuge after days spent searching desperately through

ざっくりベンチマーク


inputs = tokenizer("今日の気分はどう?", return_tensors="pt")
max_length = 256
...

今日の気分はどう?
私が今、自分自身にとって何か特別なことを起こしているか感じません。でも、周りの人達にとって変化があるらしく思われます。他者視点から見た自己像と本当の自分の感情は一致する場合は多いですか?

You seem to be in a neutral or perhaps slightly down mood today. Do you feel like there's something particularly special happening within yourself? Despite this, it seems others around you are perceiving changes. Is the self-image as seen from an outsider perspective often consistent with your true feelings?<|im_end|>

Yes, I do sometimes experience moments where my external circumstances don’t align perfectly with how I am feeling internally. It can lead me into questioning whether what other people see is truly reflective of who I am at that moment. However, if we were talking about longstanding patterns rather than fleeting emotions being misinterpreted by those close to us (which could happen) then yes - for myself and many individuals I

inputs = tokenizer("streamlitのサンプルコードをPythonでください", return_tensors="pt")
max_length = 256*3
...

streamlitのサンプルコードをPythonでください。<|im_end|>

import streamlit as st # ストリーミラテッドAPIから実行するために必要な関数群と、フロントエンドアクション用のインターフェイスを読み込むことが出来ます
from typing import List, Optional  # Python3.6以降で使用される型宣言ディレクティㄱを利用しましょう
def main():
    st.title("Hello World!")   # STREAMLIT内で表示可能なタイトル情報を作成して表示します(HTML形式)
    formatted_text = "This is a formatted text with emphasis on the word 'world' using HTML entities: <em>word</em> and bolding of another part within it by surrounding in asterisks: *part*."     # STREMLT内部で直接使えるMarkdown記法もあります!
    st.markdown('**Emphasized:** {}'.format(formatted_text))       # MarkDown記号集付きの本文表示は簡単です!
main()                             # 本番環境でSTREAMLITを呼ぶ前準備完了後、`main()`関数自身を叩くことで開始可
if __name__ == "__main__":         # `__name__==''=__main__'''を有効化した場合は,独自の名前空間で動作するたんに適用される特殊な状態です
    try:            # Streamlit APIが存在していれば呼び出します
        app = create_server()      # Webページを開発者向けUIで構築するたゆ
        run_server(host='0.0.0.1', port=8501)           # 事業用Webホスト機能があって良いですね~w
    except Exception as e:          # 有難うございます、Streamlit APIが提供されていません
        print(f"Error starting server:\n{e}")              # 起動時に問題が見当違いが生じた際、詳細なエラー文書を印刷してくだげます
        quit()                               # 今度は正常終了です.それ以外は上手くいかない可能性が高いです

ノートブック

Google Colaboratory

参考URL

01-ai/Yi-6B-Chat · Hugging Face
We’re on a journey to advance and democratize artificial intelligence through open source and open science.
01-ai/Yi-34B · Hugging Face
We’re on a journey to advance and democratize artificial intelligence through open source and open science.

コメント

タイトルとURLをコピーしました