-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.ts
More file actions
152 lines (125 loc) · 4.92 KB
/
model.ts
File metadata and controls
152 lines (125 loc) · 4.92 KB
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
import type { TrainingSample } from './context'
import type { TokenId } from './vocabulary'
export type NgramLanguageModel = {
getNextToken: (contextTokens: TokenId[]) => TokenFrequencyDistribution | undefined
train: (trainingSamples: TrainingSample[]) => void
}
export type TokenFrequencyDistribution = Map<TokenId, number>
type TemperatureAdjustedWeightEntry = {
adjustedWeight: number
tokenId: TokenId
}
/**
* Creates an n-gram language model that learns token patterns from training data.
*/
export const createNgramLanguageModel = (): NgramLanguageModel => {
const contextToNextTokenFrequencies: Map<string, TokenFrequencyDistribution> = new Map<
string,
TokenFrequencyDistribution
>()
const getNextToken = (contextTokens: TokenId[]): TokenFrequencyDistribution | undefined => {
return contextToNextTokenFrequencies.get(contextTokens.join(','))
}
const train = (samples: TrainingSample[]): void => {
for (const { contextTokens, nextToken } of samples) {
const contextKey: string = contextTokens.join(',')
if (!contextToNextTokenFrequencies.has(contextKey)) {
contextToNextTokenFrequencies.set(contextKey, new Map())
}
const frequencyDistribution: TokenFrequencyDistribution =
contextToNextTokenFrequencies.get(contextKey)!
const currentCount: number = frequencyDistribution.get(nextToken) ?? 0
frequencyDistribution.set(nextToken, currentCount + 1)
}
}
return { getNextToken, train }
}
/**
* Samples the next token from a probability distribution using either nucleus sampling or temperature-based sampling.
*/
export const sampleNextToken = (
tokenDistribution: TokenFrequencyDistribution,
temperature: number,
nucleusProbabilityThreshold: number,
): null | TokenId => {
if (nucleusProbabilityThreshold > 0 && nucleusProbabilityThreshold < 1) {
return sampleNextTokenWithNucleusSampling(
tokenDistribution,
nucleusProbabilityThreshold,
temperature,
)
} else {
return sampleNextTokenWithTemperature(tokenDistribution, temperature)
}
}
/**
* Samples the next token from a probability distribution using nucleus (top-p) sampling.
*
* Source: Wikipedia, various blog posts and articles
*/
export const sampleNextTokenWithNucleusSampling = (
tokenDistribution: TokenFrequencyDistribution,
nucleusProbabilityThreshold: number,
temperature: number,
): null | TokenId => {
const distributionEntries: [TokenId, number][] = [...tokenDistribution.entries()]
if (distributionEntries.length === 0) return null
const temperatureAdjustedWeights: TemperatureAdjustedWeightEntry[] = distributionEntries
.map(([tokenId, frequency]: [TokenId, number]) => ({
adjustedWeight: Math.pow(frequency, 1 / temperature),
tokenId,
}))
.sort(
(entryA: TemperatureAdjustedWeightEntry, entryB: TemperatureAdjustedWeightEntry): number =>
entryB.adjustedWeight - entryA.adjustedWeight,
)
const totalWeight: number = temperatureAdjustedWeights.reduce(
(sum: number, entry: TemperatureAdjustedWeightEntry): number => sum + entry.adjustedWeight,
0,
)
let cumulativeProbability: number = 0
const nucleusTokens: TemperatureAdjustedWeightEntry[] = []
for (const entry of temperatureAdjustedWeights) {
cumulativeProbability += entry.adjustedWeight / totalWeight
nucleusTokens.push(entry)
if (cumulativeProbability >= nucleusProbabilityThreshold) break
}
const nucleusTotalWeight: number = nucleusTokens.reduce(
(sum: number, entry: TemperatureAdjustedWeightEntry): number => sum + entry.adjustedWeight,
0,
)
let randomThreshold: number = Math.random() * nucleusTotalWeight
for (const entry of nucleusTokens) {
randomThreshold -= entry.adjustedWeight
if (randomThreshold <= 0) return entry.tokenId
}
return nucleusTokens[0]?.tokenId ?? null
}
/**
* Selects the next token from a probability distribution using temperature-based sampling.
*
* Source: Wikipedia, various blog posts and articles
*/
export const sampleNextTokenWithTemperature = (
tokenDistribution: TokenFrequencyDistribution,
temperature: number,
): null | TokenId => {
const distributionEntries: [TokenId, number][] = [...tokenDistribution.entries()]
if (distributionEntries.length === 0) return null
const temperatureAdjustedWeights: TemperatureAdjustedWeightEntry[] = distributionEntries.map(
([tokenId, frequency]: [TokenId, number]): TemperatureAdjustedWeightEntry => ({
adjustedWeight: Math.pow(frequency, 1 / temperature),
tokenId,
}),
)
const totalWeight: number = temperatureAdjustedWeights.reduce(
(sum: number, entry: TemperatureAdjustedWeightEntry): number => sum + entry.adjustedWeight,
0,
)
let randomThreshold: number = Math.random() * totalWeight
for (const entry of temperatureAdjustedWeights) {
randomThreshold -= entry.adjustedWeight
if (randomThreshold <= 0) return entry.tokenId
}
return temperatureAdjustedWeights[0]?.tokenId ?? null
}