Vor ein paar Wochen hatte ich eine Diskussion mit einem CFO eines Geschäftspartnerunternehmens über die Implementierung von watsonx.ai-Kapazitäten in deren eigener Lösung. Während der Diskussion über die Kosten habe ich das Wort „Token“ ausgesprochen und plötzlich herrschte Panik ?
Nachdem ich erklärt hatte, was Token sind, kam die Frage: „Wie zähle ich die Token, die wir senden und empfangen? Wie viel kostet es uns?“
Die Antwort war ganz einfach. Wir gingen zum watsonx.ai Studio Prompt Lab, gingen mit einigen einfachen Prompts hin und her und sahen dort die Anzahl der Token. Ich habe der Person auch einige sehr schöne Websites gezeigt, auf denen wir mithilfe einfacher Eingaben herausfinden können, wie viele Token wir an ein LLM senden.
Später habe ich mir gesagt, warum erstelle ich nicht meine eigene Token-Counter-Anwendung (und meine Absicht ist es, sie in Go-Sprache zu schreiben, da ich Golang schon lange nicht mehr verwendet habe!). Nun, ich dachte, es ist etwas komplizierter?
Mein erster Gedanke war, dass ich mit Regex mehr oder weniger akzeptable Ergebnisse erzielen könnte.
Ich habe die folgende Go-App eingerichtet.
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) }
Sie werden feststellen, dass ich ein Fan von GUI und Dialogfeldern bin, deshalb habe ich ein Dialogfeld implementiert, um die Eingabetextdatei auszuwählen.
Und hier ist die Textdatei (ein zufälliger Text, den ich gefunden habe?).
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.
Nachdem ich meinen Code ausgeführt habe, erhalte ich die folgende Ausgabe:
The file contains approximately 359 tokens.
Es scheint in Ordnung zu sein, aber, na ja... okay, aber... gegen welches Modell?? Und es gibt auch verschiedene Möglichkeiten, Regex zu implementieren, also zählt diese überhaupt nicht?!
Was ich herausgefunden habe, war, dass die erstere Methode nicht korrekt ist, es sei denn, wir verwenden nicht den spezifischen „Tokenizer“ für ein bestimmtes LLM. Also begann ich zu überlegen, wie ich mit einem Modell wie GPT 3.5, das schon seit einiger Zeit auf dem Markt ist, genaue Ergebnisse erzielen kann. Nach einigen Recherchen im Internet kam hier die App heraus, die ich mir ausgedacht habe.
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) }
Wie wir im obigen Code sehen können, gibt es einen Aufruf einer Python-App, die ich auf einer Microsoft-Website gefunden habe und die (weil sie implementiert wurde) ein „tiktoken“-Bibliothek, um die Anzahl der Token für gpt zu ermitteln! Auch der Modellname ist fest codiert.
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))
GPT 3.5 eingestellt habe.
Ich möchte einen Code schreiben, der vollständig in „Golang“ ist … und ich möchte ihn für alle Modelle (oder fast alle) ausführen können, die ich auf Huggingface finden kann (z. B als ibm-granite/granite-3.1–8b-instruct) ?
Dies wäre Teil 2 dieses Artikels (WIP).
Bisher erkunde ich die folgenden (großartig?) Github Repos;
Danke fürs Lesen und offen für Kommentare.
Und bis die 2. App draußen ist, bleiben Sie dran... ?
Das obige ist der detaillierte Inhalt vonZählen der Anzahl der an ein LLM in Go gesendeten Token (Teil 1). Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!