forked from pkoukk/tiktoken-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
load.go
107 lines (92 loc) · 2.42 KB
/
load.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package tiktoken
import (
"crypto/sha1"
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/google/uuid"
)
type BpeLoader interface {
LoadTiktokenBpe(tiktokenBpeFile string) (map[string]int, error)
}
func readFile(blobpath string) ([]byte, error) {
if !strings.HasPrefix(blobpath, "http://") && !strings.HasPrefix(blobpath, "https://") {
file, err := os.Open(blobpath)
if err != nil {
return nil, err
}
defer file.Close()
return ioutil.ReadAll(file)
}
// avoiding blobfile for public files helps avoid auth issues, like MFA prompts
resp, err := http.Get(blobpath)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
func readFileCached(blobpath string) ([]byte, error) {
var cacheDir string
if os.Getenv("TIKTOKEN_CACHE_DIR") != "" {
cacheDir = os.Getenv("TIKTOKEN_CACHE_DIR")
} else if os.Getenv("DATA_GYM_CACHE_DIR") != "" {
cacheDir = os.Getenv("DATA_GYM_CACHE_DIR")
} else {
cacheDir = filepath.Join(os.TempDir(), "data-gym-cache")
}
if cacheDir == "" {
// disable caching
return readFile(blobpath)
}
cacheKey := fmt.Sprintf("%x", sha1.Sum([]byte(blobpath)))
cachePath := filepath.Join(cacheDir, cacheKey)
if _, err := os.Stat(cachePath); err == nil {
return ioutil.ReadFile(cachePath)
}
contents, err := readFile(blobpath)
if err != nil {
return nil, err
}
os.MkdirAll(cacheDir, os.ModePerm)
tmpFilename := cachePath + "." + uuid.New().String() + ".tmp"
if err := ioutil.WriteFile(tmpFilename, contents, os.ModePerm); err != nil {
return nil, err
}
return contents, os.Rename(tmpFilename, cachePath)
}
func loadTiktokenBpe(tiktokenBpeFile string) (map[string]int, error) {
contents, err := readFileCached(tiktokenBpeFile)
if err != nil {
return nil, err
}
bpeRanks := make(map[string]int)
for _, line := range strings.Split(string(contents), "\n") {
if line == "" {
continue
}
parts := strings.Split(line, " ")
token, err := base64.StdEncoding.DecodeString(parts[0])
if err != nil {
return nil, err
}
rank, err := strconv.Atoi(parts[1])
if err != nil {
return nil, err
}
bpeRanks[string(token)] = rank
}
return bpeRanks, nil
}
type defaultBpeLoader struct{}
func (l *defaultBpeLoader) LoadTiktokenBpe(tiktokenBpeFile string) (map[string]int, error) {
return loadTiktokenBpe(tiktokenBpeFile)
}
func NewDefaultBpeLoader() BpeLoader {
return &defaultBpeLoader{}
}