導入
数週間前、私はビジネス パートナー企業の CFO と、自社のソリューション内での watsonx.ai 機能の実装について話し合いました。コストについての議論中に「トークン」という単語を発音してしまい、突然パニックになりました?
トークンとは何かを説明した後、次のような疑問が生じました。 「送受信するトークンをどのように数えればよいでしょうか?費用はいくらかかりますか?
答えはとても簡単でした。私たちは watsonx.ai スタジオ プロンプト ラボに行き、いくつかの簡単なプロンプトを行ったり来たりして、そこでトークンの数を確認しました。また、私はその人に、簡単な入力を使用して LLM に送信するトークンの数を確認できる非常に優れた Web サイトをいくつか紹介しました。
その後、私は自分自身に、独自のトークンカウンターアプリケーションを作ってみようかと言いました (Golang を使っていない期間が長かったので、私の目的は Go 言語で書くことです!)。そうですね、それよりももう少し複雑だと思いました?
最初の試み - 正規表現の使用
私が最初に考えたのは、正規表現を使用すると、多かれ少なかれ許容できる結果が得られるということでした。
次の Go アプリをセットアップしました。
package main import ( "bufio" "fmt" "log" "os" "regexp" "strings" "github.com/sqweek/dialog" ) // countTokens approximates the number of tokens in a text based on whitespace and punctuation. func countTokens(text string) int { // A simple regex to split text into words and punctuation tokenizer := regexp.MustCompile(`\w+|[^\w\s]`) tokens := tokenizer.FindAllString(text, -1) return len(tokens) } func main() { // Open a file dialog box and let the user select a text file filePath, err := dialog.File().Filter("Text Files", "txt").Load() if err != nil { if err.Error() == "Cancelled" { fmt.Println("File selection was cancelled.") return } log.Fatalf("Error selecting file: %v", err) } // Output the selected file name fmt.Printf("Selected file: %s\n", filePath) // Specify the file to read //filePath := "input.txt" // Open the file file, err := os.Open(filePath) if err != nil { fmt.Printf("Error opening file: %v\n", err) return } defer file.Close() // Read the file line by line var content strings.Builder scanner := bufio.NewScanner(file) for scanner.Scan() { content.WriteString(scanner.Text()) content.WriteString("\n") } if err := scanner.Err(); err != nil { fmt.Printf("Error reading file: %v\n", err) return } // Get the text content text := content.String() // Count the tokens tokenCount := countTokens(text) // Output the result fmt.Printf("The file contains approximately %d tokens.\n", tokenCount) }
私が GUI とダイアログ ボックスのファンであることがおわかりいただけると思いますが、入力テキスト ファイルを選択するダイアログ ボックスを実装しました。
そして、これがテキスト ファイルです (私が見つけたランダムなテキスト?)。
The popularity of the Rust language continues to explode; yet, many critical codebases remain authored in C, and cannot be realistically rewritten by hand. Automatically translating C to Rust is thus an appealing course of action. Several works have gone down this path, handling an ever-increasing subset of C through a variety of Rust features, such as unsafe. While the prospect of automation is appealing, producing code that relies on unsafe negates the memory safety guarantees offered by Rust, and therefore the main advantages of porting existing codebases to memory-safe languages. We instead explore a different path, and explore what it would take to translate C to safe Rust; that is, to produce code that is trivially memory safe, because it abides by Rust's type system without caveats. Our work sports several original contributions: a type-directed translation from (a subset of) C to safe Rust; a novel static analysis based on "split trees" that allows expressing C's pointer arithmetic using Rust's slices and splitting operations; an analysis that infers exactly which borrows need to be mutable; and a compilation strategy for C's struct types that is compatible with Rust's distinction between non-owned and owned allocations. We apply our methodology to existing formally verified C codebases: the HACL* cryptographic library, and binary parsers and serializers from EverParse, and show that the subset of C we support is sufficient to translate both applications to safe Rust. Our evaluation shows that for the few places that do violate Rust's aliasing discipline, automated, surgical rewrites suffice; and that the few strategic copies we insert have a negligible performance impact. Of particular note, the application of our approach to HACL* results in a 80,000 line verified cryptographic library, written in pure Rust, that implements all modern algorithms - the first of its kind.
コードを実行すると、次の出力が得られます。
The file contains approximately 359 tokens.
それは大丈夫のようですが、まあ…大丈夫ですが…どのモデルに対してですか??また、正規表現を実装するにはさまざまな方法があるため、これはまったく考慮されません ?!
2 回目の試行 - 特定のモデルに対して実行
私が理解したのは、特定の LLM に特定の「トークナイザー」を使用しない限り、前者の方法は正確ではないということです。そこで私は、しばらく前から市場に出ている gpt 3.5 などのモデルに対して正確な結果を得る方法を検討し始めました。ネットで色々調べた結果、思いついたアプリを以下に紹介します。
package main import ( "bufio" "bytes" "fmt" "log" "os" "os/exec" "github.com/joho/godotenv" "github.com/sqweek/dialog" ) func main() { // Open a file dialog box and let the user select a text file filePath, err := dialog.File().Filter("Text Files", "txt").Load() if err != nil { if err.Error() == "Cancelled" { fmt.Println("File selection was cancelled.") return } log.Fatalf("Error selecting file: %v", err) } // Output the selected file name fmt.Printf("Selected file: %s\n", filePath) // Open the file file, err := os.Open(filePath) if err != nil { fmt.Printf("Error opening file: %v\n", err) return } defer file.Close() // Read the file content var content bytes.Buffer scanner := bufio.NewScanner(file) for scanner.Scan() { content.WriteString(scanner.Text()) content.WriteString("\n") } if err := scanner.Err(); err != nil { fmt.Printf("Error reading file: %v\n", err) return } // Specify the model model := "gpt-3.5-turbo" // Execute the Python script cmd := exec.Command("python3", "tokenizer.py", model) cmd.Stdin = bytes.NewReader(content.Bytes()) output, err := cmd.Output() if err != nil { fmt.Printf("Error running tokenizer script: %v\n", err) return } // Print the token count fmt.Printf("Token count: %s", output) }
上記のコードでわかるように、Microsoft サイトで見つけた Python アプリへの呼び出しがあります。これは、(実装されているため) 「tiktoken」ライブラリを使用して、gpt のトークンの数を決定します。また、モデル名はハードコードされています。
import sys from tiktoken import encoding_for_model def count_tokens(model, text): enc = encoding_for_model(model) tokens = enc.encode(text) return len(tokens) if __name__ == "__main__": # Read model name and text from stdin model = sys.argv[1] # E.g., "gpt-3.5-turbo" text = sys.stdin.read() print(count_tokens(model, text))これはうまくいきます。前に与えた同じテキストについて、見つかったすべての Web サイトに関して正確な 366 個のトークンの数を取得し、モデルを
GPT 3.5 に設定しました。
私が書きたいのは、完全に「Golang」でコードを書きたいということです…そして、Huggingface で見つけられるすべてのモデル (またはほぼすべて) でそれを実行できるようにしたいのです (たとえば、 ibm-granite/granite-3.1–8b-instruct として) ?
これはこの記事のパート 2 (WIP) になります。
これまでのところ、私は次の (素晴らしい ?) Github リポジトリを調査しています。
- トークナイザー: https://github.com/sugarme/tokenizer
- トークナイザー: https://github.com/daulet/tokenizers
- そして最後に重要なことを言い忘れました -> go-huggingface: https://github.com/gomlx/go-huggingface?tab=readme-ov-file
結論
読んでいただきありがとうございます。コメントもお待ちしています。
そして、2 番目のアプリがリリースされるまで、ご期待ください… ?
以上がGo で LLM に送信されたトークンの数を数える (パート 1)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

GolangisidealforBuildingsCalables Systemsduetoitsefficiency andConcurrency、Whilepythonexcelsinquickscriptinganddataanalysisduetoitssimplicityand vastecosystem.golang'ssignencouragesclean、readisinediteNeditinesinedinediseNabletinedinedinedisedisedioncourase

Golangは並行性がCよりも優れていますが、Cは生の速度ではGolangよりも優れています。 1)Golangは、GoroutineとChannelを通じて効率的な並行性を達成します。これは、多数の同時タスクの処理に適しています。 2)Cコンパイラの最適化と標準ライブラリを介して、極端な最適化を必要とするアプリケーションに適したハードウェアに近い高性能を提供します。

Golangを選択する理由には、1)高い並行性パフォーマンス、2)静的タイプシステム、3)ガベージ収集メカニズム、4)豊富な標準ライブラリとエコシステムは、効率的で信頼できるソフトウェアを開発するための理想的な選択肢となります。

Golangは迅速な発展と同時シナリオに適しており、Cは極端なパフォーマンスと低レベルの制御が必要なシナリオに適しています。 1)Golangは、ごみ収集と並行機関のメカニズムを通じてパフォーマンスを向上させ、高配列Webサービス開発に適しています。 2)Cは、手動のメモリ管理とコンパイラの最適化を通じて究極のパフォーマンスを実現し、埋め込みシステム開発に適しています。

Golangは、コンピレーション時間と同時処理においてより良いパフォーマンスを発揮しますが、Cはランニング速度とメモリ管理においてより多くの利点があります。 1.Golangの編集速度は速く、迅速な発展に適しています。 2.Cは速く実行され、パフォーマンスクリティカルなアプリケーションに適しています。 3. Golangは、同時処理においてシンプルで効率的で、同時プログラミングに適しています。 4.Cマニュアルメモリ管理により、パフォーマンスが高くなりますが、開発の複雑さが向上します。

WebサービスとシステムプログラミングへのGolangのアプリケーションは、主にそのシンプルさ、効率性、並行性に反映されています。 1)Webサービスでは、Golangは、強力なHTTPライブラリと同時処理機能を介して、高性能WebアプリケーションとAPIの作成をサポートしています。 2)システムプログラミングでは、Golangはハードウェアに近い機能とC言語との互換性を使用して、オペレーティングシステムの開発と組み込みシステムに適しています。

GolangとCには、パフォーマンスの比較に独自の利点と欠点があります。1。ゴーランは、高い並行性と迅速な発展に適していますが、ごみ収集はパフォーマンスに影響を与える可能性があります。 2.Cは、パフォーマンスとハードウェア制御を高くしますが、開発の複雑さが高くなります。選択を行うときは、プロジェクトの要件とチームのスキルを包括的な方法で考慮する必要があります。

Golangは、高性能および同時プログラミングシナリオに適していますが、Pythonは迅速な開発とデータ処理に適しています。 1.Golangは、シンプルさと効率性を強調し、バックエンドサービスとマイクロサービスに適しています。 2。Pythonは、データサイエンスと機械学習に適した簡潔な構文とリッチライブラリで知られています。


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

AtomエディタMac版ダウンロード
最も人気のあるオープンソースエディター

SublimeText3 英語版
推奨: Win バージョン、コードプロンプトをサポート!

mPDF
mPDF は、UTF-8 でエンコードされた HTML から PDF ファイルを生成できる PHP ライブラリです。オリジナルの作者である Ian Back は、Web サイトから「オンザフライ」で PDF ファイルを出力し、さまざまな言語を処理するために mPDF を作成しました。 HTML2FPDF などのオリジナルのスクリプトよりも遅く、Unicode フォントを使用すると生成されるファイルが大きくなりますが、CSS スタイルなどをサポートし、多くの機能強化が施されています。 RTL (アラビア語とヘブライ語) や CJK (中国語、日本語、韓国語) を含むほぼすべての言語をサポートします。ネストされたブロックレベル要素 (P、DIV など) をサポートします。

DVWA
Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、

MinGW - Minimalist GNU for Windows
このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。
