reader.go 1.4 KB
Newer Older
xuxzh1's avatar
init  
xuxzh1 committed
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
package convert

import (
	"errors"
	"io"
	"io/fs"
	"strings"
)

type Tensor interface {
	Name() string
	Shape() []uint64
	Kind() uint32
	SetRepacker(repacker)
	WriteTo(io.Writer) (int64, error)
}

type tensorBase struct {
	name  string
	shape []uint64
	repacker
}

func (t tensorBase) Name() string {
	return t.name
}

func (t tensorBase) Shape() []uint64 {
	return t.shape
}

const (
	tensorKindF32 uint32 = iota
	tensorKindF16
)

func (t tensorBase) Kind() uint32 {
	if strings.HasSuffix(t.name, ".block_sparse_moe.gate.weight") {
		return 0
	}

	switch len(t.shape) {
	case 0:
		panic("invalid tensor shape")
	case 1:
		return tensorKindF32
	default:
		return tensorKindF16
	}
}

func (t *tensorBase) SetRepacker(fn repacker) {
	t.repacker = fn
}

type repacker func(string, []float32, []uint64) ([]float32, error)

func parseTensors(fsys fs.FS) ([]Tensor, error) {
	patterns := []struct {
		Pattern string
		Func    func(fs.FS, ...string) ([]Tensor, error)
	}{
		{"model-*-of-*.safetensors", parseSafetensors},
		{"model.safetensors", parseSafetensors},
		{"pytorch_model-*-of-*.bin", parseTorch},
		{"pytorch_model.bin", parseTorch},
		{"consolidated.*.pth", parseTorch},
	}

	for _, pattern := range patterns {
		matches, err := fs.Glob(fsys, pattern.Pattern)
		if err != nil {
			return nil, err
		}

		if len(matches) > 0 {
			return pattern.Func(fsys, matches...)
		}
	}

	return nil, errors.New("unknown tensor format")
}