summaryrefslogtreecommitdiff
path: root/research/knobloch/stats.go
blob: e462e1b522e9f60e116bfb290df5ac3f2575e9ab (plain)
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
package knobloch

import (
	"encoding/csv"
	"os"
	"slices"
	"strconv"

	"go.jknobloc.com/x/tokenizer/bpe"
	"gonum.org/v1/gonum/stat"
)

// FrequencyStats summarizes how much of a tokenizer's vocabulary, and how much
// of its token mass, lines up with the morpheme inventory.
type FrequencyStats struct {
	Model string

	// types are distinct vocabulary entries, occurrences are corpus counts
	Vocab          int
	Used           int
	MorphemeTypes  int
	MorphemeTokens int64
	OtherTokens    int64

	MorphemeMedian int
	OtherMedian    int

	// morphemes among the 1000 most frequent tokens
	MorphemeTop1000 int

	// RankID is Spearman's correlation between a token's vocabulary position and
	// its corpus frequency rank. A strict frequency objective merges the most
	// frequent pair first, so position and frequency rank move together and this
	// sits near 1. The further a tokenizer departs from that objective, the more
	// the two come apart, so it measures deviation from the frequency criterion
	// independently of what the competing criterion happens to be.
	RankID float64
}

func (s FrequencyStats) TypeShare() float64 {
	if s.Used == 0 {
		return 0
	}

	return float64(s.MorphemeTypes) / float64(s.Used)
}

func (s FrequencyStats) TokenShare() float64 {
	total := s.MorphemeTokens + s.OtherTokens

	if total == 0 {
		return 0
	}

	return float64(s.MorphemeTokens) / float64(total)
}

func NewFrequencyStats(model string, r []int, t *bpe.Tokenizer) (FrequencyStats, error) {
	morph, err := morphemes()

	if err != nil {
		return FrequencyStats{}, err
	}

	itoa := bpe.Itoa(t)

	s := FrequencyStats{
		Model: model,
		Vocab: len(r),
	}

	var mFreq, oFreq []int

	for id, f := range r {
		if f <= 0 {
			continue
		}

		s.Used++

		if _, ok := morph[itoa[int64(id)]]; ok {
			s.MorphemeTypes++
			s.MorphemeTokens += int64(f)

			mFreq = append(mFreq, f)
		} else {
			s.OtherTokens += int64(f)

			oFreq = append(oFreq, f)
		}
	}

	slices.Sort(mFreq)
	slices.Sort(oFreq)

	s.MorphemeMedian = median(mFreq)
	s.OtherMedian = median(oFreq)

	ids := make([]int, 0, s.Used)

	for id, f := range r {
		if f > 0 {
			ids = append(ids, id)
		}
	}

	slices.SortFunc(ids, func(a, b int) int {
		return r[b] - r[a]
	})

	for _, id := range ids[:min(1000, len(ids))] {
		if _, ok := morph[itoa[int64(id)]]; ok {
			s.MorphemeTop1000++
		}
	}

	s.RankID = rankIDCorrelation(r)

	return s, nil
}

// rankIDCorrelation is Spearman's rho between vocabulary position and corpus
// frequency rank over the used tokens. gonum has no Spearman, so the ranks are
// built here and fed to Pearson, which is the same thing by definition.
func rankIDCorrelation(r []int) float64 {
	ids := make([]int, 0, len(r))

	for id, f := range r {
		if f > 0 {
			ids = append(ids, id)
		}
	}

	if len(ids) < 2 {
		return 0
	}

	// ids is ascending and has no duplicates, so a token's id rank is its index
	position := make([]float64, len(ids))

	for i := range ids {
		position[i] = float64(i + 1)
	}

	order := slices.Clone(ids)

	slices.SortFunc(order, func(a, b int) int {
		return r[b] - r[a]
	})

	// tied counts share the average of the ranks they span
	ranks := make(map[int]float64, len(order))

	for i := 0; i < len(order); {
		j := i

		for j+1 < len(order) && r[order[j+1]] == r[order[i]] {
			j++
		}

		avg := float64(i+j+2) / 2

		for k := i; k <= j; k++ {
			ranks[order[k]] = avg
		}

		i = j + 1
	}

	frequency := make([]float64, len(ids))

	for i, id := range ids {
		frequency[i] = ranks[id]
	}

	return stat.Correlation(position, frequency, nil)
}

func median(v []int) int {
	if len(v) == 0 {
		return 0
	}

	return v[len(v)/2]
}

var frequencyStatsHeader = []string{
	"model", "vocab", "used", "morpheme_types", "type_share",
	"morpheme_tokens", "other_tokens", "token_share",
	"morpheme_median", "other_median", "morpheme_top_1000", "rank_id_spearman",
}

func (s FrequencyStats) row() []string {
	return []string{
		s.Model,
		strconv.Itoa(s.Vocab),
		strconv.Itoa(s.Used),
		strconv.Itoa(s.MorphemeTypes),
		strconv.FormatFloat(s.TypeShare(), 'f', 4, 64),
		strconv.FormatInt(s.MorphemeTokens, 10),
		strconv.FormatInt(s.OtherTokens, 10),
		strconv.FormatFloat(s.TokenShare(), 'f', 4, 64),
		strconv.Itoa(s.MorphemeMedian),
		strconv.Itoa(s.OtherMedian),
		strconv.Itoa(s.MorphemeTop1000),
		strconv.FormatFloat(s.RankID, 'f', 4, 64),
	}
}

// AppendFrequencyStats adds one row per run so numbers for different tokenizers
// accumulate in a single table.
func AppendFrequencyStats(name string, s FrequencyStats) error {
	_, err := os.Stat(name)

	if err != nil && !os.IsNotExist(err) {
		return err
	}

	fresh := os.IsNotExist(err)

	file, err := os.OpenFile(name, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)

	if err != nil {
		return err
	}

	defer file.Close()

	w := csv.NewWriter(file)

	if fresh {
		if err := w.Write(frequencyStatsHeader); err != nil {
			return err
		}
	}

	if err := w.Write(s.row()); err != nil {
		return err
	}

	w.Flush()

	return w.Error()
}