導入
これは、選択したテキストに基づいてユーザーが LLM に送信するトークンの数を決定する Go アプリケーションを作成する作業の 2 番目の部分です。
前の記事で、Golang のみで書かれたものを構築したいと述べましたが、私が調べた Github リポジトリの中で、これが本当に優れているようです: go-hggingface。コードは非常に新しいように見えますが、私にとっては「ある程度」機能しています。
実装
まず、コードは Hugginface にアクセスして、LLM に付属するすべての「トークナイザー」のリストを取得します。そのため、ユーザーは HF トークンを持っている必要があります。そこで、次のようにトークンを .env ファイルに置きました。
HF_TOKEN="your-huggingface-token"
次に、次のページ (https://github.com/gomlx/go-huggingface?tab=readme-ov-file) にある例を使用して、それを中心に独自のコードを構築しました。
package main import ( "bytes" "fmt" "log" "os" "os/exec" "runtime" "github.com/gomlx/go-huggingface/hub" "github.com/gomlx/go-huggingface/tokenizers" "github.com/joho/godotenv" "github.com/sqweek/dialog" "fyne.io/fyne/v2" "fyne.io/fyne/v2/app" "fyne.io/fyne/v2/container" "fyne.io/fyne/v2/widget" //"github.com/inancgumus/scree" ) var ( // Model IDs we use for testing. hfModelIDs = []string{ "ibm-granite/granite-3.1-8b-instruct", "meta-llama/Llama-3.3-70B-Instruct", "mistralai/Mistral-7B-Instruct-v0.3", "google/gemma-2-2b-it", "sentence-transformers/all-MiniLM-L6-v2", "protectai/deberta-v3-base-zeroshot-v1-onnx", "KnightsAnalytics/distilbert-base-uncased-finetuned-sst-2-english", "KnightsAnalytics/distilbert-NER", "SamLowe/roberta-base-go_emotions-onnx", } ) func runCmd(name string, arg ...string) { cmd := exec.Command(name, arg...) cmd.Stdout = os.Stdout cmd.Run() } func ClearTerminal() { switch runtime.GOOS { case "darwin": runCmd("clear") case "linux": runCmd("clear") case "windows": runCmd("cmd", "/c", "cls") default: runCmd("clear") } } func FileSelectionDialog() string { // 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.") } log.Fatalf("Error selecting file: %v", err) } // Output the selected file name fmt.Printf("Selected file: %s\n", filePath) return filePath } func main() { var filePath string // read the '.env' file err := godotenv.Load() if err != nil { log.Fatal("Error loading .env file") } // get the value of the 'HF_TOKEN' environment variable hfAuthToken := os.Getenv("HF_TOKEN") if hfAuthToken == "" { log.Fatal("HF_TOKEN environment variable is not set") } // to display a list of LLMs to determine the # of tokens later on regarding the given text var llm string = "" var modelID string = "" myApp := app.New() myWindow := myApp.NewWindow("Select a LLM in the list") items := hfModelIDs // Label to display the selected item selectedItem := widget.NewLabel("Selected LLM: None") // Create a list widget list := widget.NewList( func() int { // Return the number of items in the list return len(items) }, func() fyne.CanvasObject { // Template for each list item return widget.NewLabel("Template") }, func(id widget.ListItemID, obj fyne.CanvasObject) { // Update the template with the actual data obj.(*widget.Label).SetText(items[id]) }, ) // Handle list item selection list.OnSelected = func(id widget.ListItemID) { selectedItem.SetText("Selected LLM:" + items[id]) llm = items[id] } // Layout with the list and selected item label content := container.NewVBox( list, selectedItem, ) // Set the content of the window myWindow.SetContent(content) myWindow.Resize(fyne.NewSize(300, 400)) myWindow.ShowAndRun() ClearTerminal() fmt.Printf("Selected LLM: %s\n", llm) ////// //List files for the selected model for _, modelID := range hfModelIDs { if modelID == llm { fmt.Printf("\n%s:\n", modelID) repo := hub.New(modelID).WithAuth(hfAuthToken) for fileName, err := range repo.IterFileNames() { if err != nil { panic(err) } fmt.Printf("fileName\t%s\n", fileName) fmt.Printf("repo\t%s\n", repo) fmt.Printf("modelID\t%s\n", modelID) } } } //List tokenizer classes for the selected model for _, modelID := range hfModelIDs { if modelID == llm { fmt.Printf("\n%s:\n", modelID) repo := hub.New(modelID).WithAuth(hfAuthToken) fmt.Printf("\trepo=%s\n", repo) config, err := tokenizers.GetConfig(repo) if err != nil { panic(err) } fmt.Printf("\ttokenizer_class=%s\n", config.TokenizerClass) } } // Models URL -> "https://huggingface.co/api/models" repo := hub.New(modelID).WithAuth(hfAuthToken) tokenizer, err := tokenizers.New(repo) if err != nil { panic(err) } // call file selection dialogbox filePath = FileSelectionDialog() // Open the file filerc, err := os.Open(filePath) if err != nil { fmt.Printf("Error opening file: %v\n", err) return } defer filerc.Close() // Put the text file content into a buffer and convert it to a string. buf := new(bytes.Buffer) buf.ReadFrom(filerc) sentence := buf.String() tokens := tokenizer.Encode(sentence) fmt.Println("Sentence:\n", sentence) fmt.Printf("Tokens: \t%v\n", tokens) }
「hfModelIDs」の「var」セクションに、IBM の Granite、Meta の LLama、さらに Mistral モデルなどの新しい参照を追加しました。
Huggingface トークンは直接取得され、Go コード内でも読み取られます。
LLM のリストを表示するダイアログ ボックス (最終的には変更します)、ファイルからテキストを追加するダイアログ ボックス (私はそのようなものが大好きです?)、およびクリアするためのコード行を追加しました。画面を掃除しますか?!
入力テキストは次のとおりです。
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.
テスト
コードを実行すると、目的の LLM を選択できるダイアログが表示されます。
すべてがうまくいった場合、次のステップは「トークナイザー」ファイルをローカルにダウンロードすることです (Github リポジトリの説明を参照)。その後、評価する内容を含むテキスト ファイルを選択するダイアログ ボックスが表示されます。トークンの数。
これまでのところ、Meta LLama と Google の「google/gemma-2–2b-it」モデルへのアクセスを要求し、アクセスが許可されるのを待っています。
google/gemma-2-2b-it: repo=google/gemma-2-2b-it panic: request for metadata from "https://huggingface.co/google/gemma-2-2b-it/resolve/299a8560bedf22ed1c72a8a11e7dce4a7f9f51f8/tokenizer_config.json" failed with the following message: "403 Forbidden"
結論
私が意図していたものを達成するための正しい道を進んでいると思います。トークンの数を決定できる Golang プログラムは、ユーザーのクエリが LLM に送信されるものです。
このプロジェクトの唯一の目的は、さまざまな LLM に対するクエリ内のトークン数の決定の背後にある内部システムを学習し、その計算方法を発見することです。
読んでいただきありがとうございます。コメントもお待ちしています。
そして最終的な結論まで、ご期待ください… ?
以上がGo で LLM に送信されたトークンの数を数える (パート 2)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

Goの「文字列」パッケージは、文字列操作を効率的かつシンプルにするための豊富な機能を提供します。 1)文字列を使用して()サブストリングを確認します。 2)Strings.split()を使用してデータを解析できますが、パフォーマンスの問題を回避するには注意して使用する必要があります。 3)文字列join()は文字列のフォーマットに適していますが、小さなデータセットの場合、ループ=はより効率的です。 4)大きな文字列の場合、文字列を使用して文字列を構築する方が効率的です。

GOは、文字列操作に「文字列」パッケージを使用します。 1)文字列を使用して、関数を調整して文字列をスプライスします。 2)文字列を使用して、コンテイン関数を使用してサブストリングを見つけます。 3)文字列を使用して、文字列を交換します。これらの機能は効率的で使いやすく、さまざまな文字列処理タスクに適しています。

byteSpackageIngoisESSENTINEFOREFFICTIENTBYTESLICEMANIPULATION、functionslikeContains、andReplaceforseding andmodyifiedbinarydata.itenhancesperformance andCodereadability、make dakeatavitaltoolfor forhandlingbingbinarydata、networkprotocols、andfilei

GOは、バイナリエンコードとデコードに「エンコード/バイナリ」パッケージを使用します。 1)このパッケージは、binary.writeとbinary.read関数を作成して、データを書き込み、読み取ります。 2)正しいエンディアン(BigendianやLittleendianなど)の選択に注意してください。 3)データのアラインメントとエラー処理も重要です。データの正確性とパフォーマンスを確保します。

Encoding/binaryPackageIngoiseffictevectiveforptimizingdueToitssuportforendiannessandannessandAhandling.toenhanceperformance:1)usebinary.native.nativedianfornatiannesstoavoidbyteswapping.2)batchedandandandwriteTerationtoredutei/ober

GOのBYTESパッケージは、主にバイトスライスを効率的に処理するために使用されます。 1)bytes.bufferを使用すると、弦のスプライシングを効率的に実行して、不必要なメモリの割り当てを避けます。 2)バイト機能を使用して、バイトスライスをすばやく比較します。 3)bytes.index、bytes.split、bytes.replaceall関数は、バイトスライスの検索と操作に使用できますが、パフォーマンスの問題に注意する必要があります。

バイトパッケージは、バイトスライスを効率的に処理するためのさまざまな機能を提供します。 1)bytes.containsを使用して、バイトシーケンスを確認します。 2)bytes.splitを使用してバイトスライスを分割します。 3)バイトシーケンスバイトを交換します。 4)bytes.joinを使用して、複数のバイトスライスを接続します。 5)bytes.bufferを使用してデータを作成します。 6)エラー処理とデータ検証のためのBYTES.MAPの組み合わせ。


ホットAIツール

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

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

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

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

人気の記事

ホットツール

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

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

SAP NetWeaver Server Adapter for Eclipse
Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

PhpStorm Mac バージョン
最新(2018.2.1)のプロフェッショナル向けPHP統合開発ツール

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