adaptive-memory-multi-model-router 2.14.18 → 2.14.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/benchmark-results.json +24 -24
- package/dist/routing/advancedRouter.js +13 -11
- package/dist/routing/advancedRouter.js.map +1 -1
- package/dist/utils/costUtils.d.ts +57 -0
- package/dist/utils/costUtils.js +150 -0
- package/dist/utils/costUtils.js.map +1 -0
- package/dist/utils/sorting.d.ts +12 -0
- package/dist/utils/sorting.js +37 -0
- package/dist/utils/sorting.js.map +1 -0
- package/package.json +1 -1
- package/research/ensemble-voting.md +324 -0
- package/research/loss-functions.md +545 -0
- package/src/routing/advancedRouter.ts +16 -12
- package/src/utils/costUtils.ts +157 -0
- package/src/utils/sorting.ts +42 -0
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Log-scale cost utilities for A3M Router
|
|
3
|
+
*
|
|
4
|
+
* Provides better differentiation across cost ranges:
|
|
5
|
+
* - Free models get score 1.0
|
|
6
|
+
* - $0.05/1K vs $0.10/1K get meaningfully different scores
|
|
7
|
+
* - $0.10/1K vs $10/1K get much larger differentiation than linear scaling
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Log-scale cost score (0-1, lower cost = higher score)
|
|
12
|
+
* Uses log scale to better differentiate mid-range costs
|
|
13
|
+
*
|
|
14
|
+
* @param costPer1K - Cost per 1K tokens (input or output)
|
|
15
|
+
* @param minCost - Minimum cost boundary (default: $0.01)
|
|
16
|
+
* @param maxCost - Maximum cost boundary (default: $10)
|
|
17
|
+
* @returns Score from 0 to 1 (higher = cheaper)
|
|
18
|
+
*/
|
|
19
|
+
export function logScaleCostScore(costPer1K: number, minCost = 0.01, maxCost = 10): number {
|
|
20
|
+
// Handle free/zero cost models
|
|
21
|
+
if (costPer1K <= 0) return 1.0;
|
|
22
|
+
|
|
23
|
+
// Normalize to log scale between minCost and maxCost
|
|
24
|
+
const logMin = Math.log(minCost);
|
|
25
|
+
const logMax = Math.log(maxCost);
|
|
26
|
+
const logCost = Math.log(Math.max(costPer1K, minCost));
|
|
27
|
+
|
|
28
|
+
// Inverse: lower cost = higher score
|
|
29
|
+
return 1 - ((logCost - logMin) / (logMax - logMin));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Combined cost score (input + output weighted)
|
|
34
|
+
*
|
|
35
|
+
* @param inputCostPer1K - Input cost per 1K tokens
|
|
36
|
+
* @param outputCostPer1K - Output cost per 1K tokens
|
|
37
|
+
* @param outputWeight - Weight for output cost (default: 0.5)
|
|
38
|
+
* @returns Combined log-scale cost score
|
|
39
|
+
*/
|
|
40
|
+
export function combinedCostScore(inputCostPer1K: number, outputCostPer1K: number, outputWeight = 0.5): number {
|
|
41
|
+
const inputScore = logScaleCostScore(inputCostPer1K);
|
|
42
|
+
const outputScore = logScaleCostScore(outputCostPer1K);
|
|
43
|
+
return inputScore * (1 - outputWeight) + outputScore * outputWeight;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Cost margin loss for training
|
|
48
|
+
* Encourages routing to significantly cheaper models
|
|
49
|
+
*
|
|
50
|
+
* @param selectedCost - Cost of selected model
|
|
51
|
+
* @param alternativeCost - Cost of alternative model
|
|
52
|
+
* @param margin - Minimum margin threshold (default: 0.1 = 10%)
|
|
53
|
+
* @returns Loss value (0 if no significant saving available)
|
|
54
|
+
*/
|
|
55
|
+
export function costMarginLoss(
|
|
56
|
+
selectedCost: number,
|
|
57
|
+
alternativeCost: number,
|
|
58
|
+
margin = 0.1
|
|
59
|
+
): number {
|
|
60
|
+
// No loss if alternative is not cheaper
|
|
61
|
+
if (alternativeCost <= selectedCost) return 0;
|
|
62
|
+
|
|
63
|
+
// Calculate saving ratio: how much cheaper is alternative?
|
|
64
|
+
const savingRatio = (alternativeCost - selectedCost) / alternativeCost;
|
|
65
|
+
|
|
66
|
+
// Loss is how much we missed the margin threshold
|
|
67
|
+
return Math.max(0, margin - savingRatio);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Quality-adjusted cost score
|
|
72
|
+
* Normalizes cost score by model quality to prioritize
|
|
73
|
+
* cost-efficient models that are also high quality
|
|
74
|
+
*
|
|
75
|
+
* @param costScore - Raw log-scale cost score (0-1)
|
|
76
|
+
* @param qualityScore - Model quality score (0-1)
|
|
77
|
+
* @returns Quality-adjusted cost score
|
|
78
|
+
*/
|
|
79
|
+
export function qualityAdjustedCostScore(costScore: number, qualityScore: number): number {
|
|
80
|
+
// Combine: prefer high quality + low cost
|
|
81
|
+
return costScore * (0.3 + 0.7 * qualityScore);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Budget-aware cost penalty
|
|
86
|
+
* Applies stronger penalty for expensive models when budget is tight
|
|
87
|
+
*
|
|
88
|
+
* @param costPer1K - Cost per 1K tokens
|
|
89
|
+
* @param budgetMultiplier - Budget pressure (0.5 = tight, 1.0 = normal, 2.0 = generous)
|
|
90
|
+
* @returns Adjusted cost score
|
|
91
|
+
*/
|
|
92
|
+
export function budgetAwareCostScore(costPer1K: number, budgetMultiplier: number = 1.0): number {
|
|
93
|
+
const baseScore = logScaleCostScore(costPer1K);
|
|
94
|
+
|
|
95
|
+
// Adjust penalty based on budget
|
|
96
|
+
// Low budget (multiplier < 1) → stronger preference for cheap
|
|
97
|
+
// High budget (multiplier > 1) → more tolerant of expensive
|
|
98
|
+
const adjustment = Math.pow(baseScore, 1 / budgetMultiplier);
|
|
99
|
+
|
|
100
|
+
return adjustment;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// ============================================================
|
|
104
|
+
// VALIDATION TESTS (can be run with: node src/utils/costUtils.ts)
|
|
105
|
+
// ============================================================
|
|
106
|
+
|
|
107
|
+
export function runValidationTests(): void {
|
|
108
|
+
const tests = [
|
|
109
|
+
// [cost, expectedBehavior]
|
|
110
|
+
[0, 1.0, "free model → score 1.0"],
|
|
111
|
+
[0.01, 1.0, "$0.01 → score 1.0 (at min boundary)"],
|
|
112
|
+
[0.05, 0.62, "$0.05 → high score (cheap)"],
|
|
113
|
+
[0.10, 0.52, "$0.10 → moderate score"],
|
|
114
|
+
[1.00, 0.30, "$1.00 → lower score"],
|
|
115
|
+
[10.0, 0.0, "$10.00 → score 0.0 (at max boundary)"],
|
|
116
|
+
|
|
117
|
+
// Check relative ordering
|
|
118
|
+
[0.05, "higher than 0.10", "verification"],
|
|
119
|
+
[0.10, "higher than 1.00", "verification"],
|
|
120
|
+
[1.00, "higher than 10.00", "verification"],
|
|
121
|
+
];
|
|
122
|
+
|
|
123
|
+
console.log("Log-Scale Cost Score Validation:");
|
|
124
|
+
console.log("=".repeat(50));
|
|
125
|
+
|
|
126
|
+
let passed = 0;
|
|
127
|
+
let failed = 0;
|
|
128
|
+
|
|
129
|
+
for (const test of tests) {
|
|
130
|
+
const cost = test[0] as number;
|
|
131
|
+
const expected = test[1];
|
|
132
|
+
const desc = test[2] as string;
|
|
133
|
+
|
|
134
|
+
const score = logScaleCostScore(cost);
|
|
135
|
+
|
|
136
|
+
if (typeof expected === "number") {
|
|
137
|
+
const ok = Math.abs(score - expected) < 0.02;
|
|
138
|
+
console.log(` ${ok ? "✓" : "✗"} ${desc}: cost=$${cost} → score=${score.toFixed(3)} (expected ~${expected})`);
|
|
139
|
+
if (ok) passed++; else failed++;
|
|
140
|
+
} else {
|
|
141
|
+
// Verification test
|
|
142
|
+
const compareCost = parseFloat(desc.split(" ")[0]);
|
|
143
|
+
const compareScore = logScaleCostScore(compareCost);
|
|
144
|
+
const ok = score > compareScore;
|
|
145
|
+
console.log(` ${ok ? "✓" : "✗"} ${desc}: ${cost} > ${compareCost} (${score.toFixed(3)} > ${compareScore.toFixed(3)})`);
|
|
146
|
+
if (ok) passed++; else failed++;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
console.log("=".repeat(50));
|
|
151
|
+
console.log(`Results: ${passed} passed, ${failed} failed`);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Run if called directly
|
|
155
|
+
if (require.main === module) {
|
|
156
|
+
runValidationTests();
|
|
157
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Quickselect algorithm for O(n) top-K selection
|
|
3
|
+
* Returns top k elements sorted descending by compare function
|
|
4
|
+
*
|
|
5
|
+
* Best case: O(n), Worst case: O(n log n), Average: O(n)
|
|
6
|
+
* vs Timsort O(n log n) for full sort + O(k log n) for top-k slice
|
|
7
|
+
*/
|
|
8
|
+
export function quickselectTopK<T>(
|
|
9
|
+
arr: T[],
|
|
10
|
+
k: number,
|
|
11
|
+
compare: (a: T) => number
|
|
12
|
+
): T[] {
|
|
13
|
+
if (arr.length <= k) {
|
|
14
|
+
return arr.slice().sort((a, b) => compare(b) - compare(a));
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const pivotIndex = Math.floor(Math.random() * arr.length);
|
|
18
|
+
const pivotVal = compare(arr[pivotIndex]);
|
|
19
|
+
|
|
20
|
+
const left = arr.filter(a => compare(a) > pivotVal);
|
|
21
|
+
const right = arr.filter(a => compare(a) < pivotVal);
|
|
22
|
+
const middle = arr.filter(a => compare(a) === pivotVal);
|
|
23
|
+
|
|
24
|
+
if (left.length >= k) {
|
|
25
|
+
return quickselectTopK(left, k, compare);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const needed = k - left.length;
|
|
29
|
+
if (needed <= middle.length) {
|
|
30
|
+
return [...left, ...middle.slice(0, needed)];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
return [...left, ...middle, ...quickselectTopK(right, k - left.length - middle.length, compare)];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Select top candidate using Quickselect
|
|
38
|
+
*/
|
|
39
|
+
export function selectTop<T>(arr: T[], compare: (a: T) => number): T | undefined {
|
|
40
|
+
const result = quickselectTopK(arr, 1, compare);
|
|
41
|
+
return result[0];
|
|
42
|
+
}
|