@latens/sdk 0.0.0-stage → 1.3.0
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/LICENSE +21 -0
- package/README.md +108 -2
- package/dist/calculator.d.ts +2 -0
- package/dist/calculator.js +30 -0
- package/dist/client.d.ts +78 -0
- package/dist/client.js +151 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/normalizer.d.ts +2 -0
- package/dist/normalizer.js +40 -0
- package/dist/sizing.d.ts +13 -0
- package/dist/sizing.js +248 -0
- package/dist/standing.d.ts +20 -0
- package/dist/standing.js +99 -0
- package/dist/types.d.ts +230 -0
- package/dist/types.js +1 -0
- package/openapi/openapi.v3.1.json +410 -0
- package/package.json +49 -4
- package/src/calculator.ts +43 -0
- package/src/client.ts +272 -0
- package/src/index.ts +6 -0
- package/src/normalizer.ts +43 -0
- package/src/sizing.ts +335 -0
- package/src/standing.ts +126 -0
- package/src/types.ts +278 -0
package/src/client.ts
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import { estimateLlmVramRequirements, rankOffersByTco } from "./sizing.js";
|
|
2
|
+
import { isValidEvmAddress } from "./standing.js";
|
|
3
|
+
import type {
|
|
4
|
+
AgentCalculateInput,
|
|
5
|
+
AgentOffersQuery,
|
|
6
|
+
AgentOffersSort,
|
|
7
|
+
GpuPriceHistoryQuery,
|
|
8
|
+
GpuPriceHistoryResponse,
|
|
9
|
+
HolderTierId,
|
|
10
|
+
LlmSizingInput,
|
|
11
|
+
LlmSizingResult,
|
|
12
|
+
NormalizedGpuOffer,
|
|
13
|
+
OfferTcoComparisonOptions,
|
|
14
|
+
OfferTcoComparisonResult,
|
|
15
|
+
TokenStandingResponse,
|
|
16
|
+
} from "./types.js";
|
|
17
|
+
|
|
18
|
+
export interface LatensClientOptions {
|
|
19
|
+
baseUrl?: string;
|
|
20
|
+
walletAddress?: string;
|
|
21
|
+
fetchImpl?: typeof fetch;
|
|
22
|
+
timeoutMs?: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export class LatensReadOnlyClient {
|
|
26
|
+
private readonly baseUrl: string;
|
|
27
|
+
private readonly walletAddress: string | null;
|
|
28
|
+
private readonly fetcher: typeof fetch;
|
|
29
|
+
private readonly timeoutMs: number;
|
|
30
|
+
|
|
31
|
+
constructor(options?: LatensClientOptions) {
|
|
32
|
+
this.baseUrl = (options?.baseUrl ?? "https://latens.trade").replace(/\/+$/, "");
|
|
33
|
+
const candidate = options?.walletAddress?.trim() ?? "";
|
|
34
|
+
this.walletAddress = isValidEvmAddress(candidate) ? candidate : null;
|
|
35
|
+
this.fetcher = options?.fetchImpl ?? fetch;
|
|
36
|
+
this.timeoutMs = options?.timeoutMs ?? 15_000;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async listOffers(query: AgentOffersQuery = {}): Promise<{
|
|
40
|
+
count: number;
|
|
41
|
+
total: number;
|
|
42
|
+
offset: number;
|
|
43
|
+
limit: number;
|
|
44
|
+
sort: AgentOffersSort;
|
|
45
|
+
next_offset: number | null;
|
|
46
|
+
offers: NormalizedGpuOffer[];
|
|
47
|
+
data: NormalizedGpuOffer[];
|
|
48
|
+
last_synced_at?: string | null;
|
|
49
|
+
}> {
|
|
50
|
+
const params = new URLSearchParams();
|
|
51
|
+
const resolvedModel = query.model ?? query.gpu_model;
|
|
52
|
+
const resolvedMaxPrice = query.max_price_per_gpu_usd ?? query.max_hourly_usd;
|
|
53
|
+
|
|
54
|
+
if (resolvedModel) params.set("model", resolvedModel);
|
|
55
|
+
if (query.provider) params.set("provider", query.provider);
|
|
56
|
+
if (query.category) params.set("category", query.category);
|
|
57
|
+
if (query.min_vram_gb !== undefined) params.set("min_vram_gb", String(query.min_vram_gb));
|
|
58
|
+
if (resolvedMaxPrice !== undefined) {
|
|
59
|
+
params.set("max_price_per_gpu_usd", String(resolvedMaxPrice));
|
|
60
|
+
}
|
|
61
|
+
if (query.gpu_count !== undefined) params.set("gpu_count", String(query.gpu_count));
|
|
62
|
+
if (query.region) params.set("region", query.region);
|
|
63
|
+
if (query.available_only !== undefined) {
|
|
64
|
+
params.set("available_only", query.available_only ? "true" : "false");
|
|
65
|
+
}
|
|
66
|
+
if (query.sort) params.set("sort", query.sort);
|
|
67
|
+
if (query.offset !== undefined) params.set("offset", String(query.offset));
|
|
68
|
+
if (query.limit !== undefined) params.set("limit", String(query.limit));
|
|
69
|
+
|
|
70
|
+
const qs = params.toString();
|
|
71
|
+
const raw = await this.requestJson<{
|
|
72
|
+
count: number;
|
|
73
|
+
total?: number;
|
|
74
|
+
offset?: number;
|
|
75
|
+
limit?: number;
|
|
76
|
+
sort?: AgentOffersSort;
|
|
77
|
+
next_offset?: number | null;
|
|
78
|
+
data?: NormalizedGpuOffer[];
|
|
79
|
+
offers?: NormalizedGpuOffer[];
|
|
80
|
+
last_synced_at?: string | null;
|
|
81
|
+
}>(`/api/v1/agent/offers${qs ? `?${qs}` : ""}`);
|
|
82
|
+
|
|
83
|
+
const list = raw.data ?? raw.offers ?? [];
|
|
84
|
+
const offset = raw.offset ?? query.offset ?? 0;
|
|
85
|
+
const limit = raw.limit ?? query.limit ?? 50;
|
|
86
|
+
const total = raw.total ?? list.length;
|
|
87
|
+
const nextOffset =
|
|
88
|
+
raw.next_offset !== undefined
|
|
89
|
+
? raw.next_offset
|
|
90
|
+
: offset + list.length < total
|
|
91
|
+
? offset + list.length
|
|
92
|
+
: null;
|
|
93
|
+
|
|
94
|
+
return {
|
|
95
|
+
count: raw.count ?? list.length,
|
|
96
|
+
total,
|
|
97
|
+
offset,
|
|
98
|
+
limit,
|
|
99
|
+
sort: raw.sort ?? query.sort ?? "price_asc",
|
|
100
|
+
next_offset: nextOffset,
|
|
101
|
+
offers: list,
|
|
102
|
+
data: list,
|
|
103
|
+
last_synced_at: raw.last_synced_at,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async listModels(): Promise<{
|
|
108
|
+
count: number;
|
|
109
|
+
models: Array<{
|
|
110
|
+
gpu_model: string;
|
|
111
|
+
manufacturer: string;
|
|
112
|
+
available_offer_count: number;
|
|
113
|
+
min_price_per_gpu_usd: number;
|
|
114
|
+
median_price_per_gpu_usd: number;
|
|
115
|
+
vram_per_gpu_gb: number;
|
|
116
|
+
providers: string[];
|
|
117
|
+
}>;
|
|
118
|
+
}> {
|
|
119
|
+
const raw = await this.requestJson<{
|
|
120
|
+
count: number;
|
|
121
|
+
data?: Array<{
|
|
122
|
+
gpu_model: string;
|
|
123
|
+
manufacturer: string;
|
|
124
|
+
available_offer_count: number;
|
|
125
|
+
min_price_per_gpu_usd: number;
|
|
126
|
+
median_price_per_gpu_usd: number;
|
|
127
|
+
vram_per_gpu_gb: number;
|
|
128
|
+
providers: string[];
|
|
129
|
+
}>;
|
|
130
|
+
models?: Array<{
|
|
131
|
+
gpu_model: string;
|
|
132
|
+
manufacturer: string;
|
|
133
|
+
available_offer_count: number;
|
|
134
|
+
min_price_per_gpu_usd: number;
|
|
135
|
+
median_price_per_gpu_usd: number;
|
|
136
|
+
vram_per_gpu_gb: number;
|
|
137
|
+
providers: string[];
|
|
138
|
+
}>;
|
|
139
|
+
}>("/api/v1/agent/models");
|
|
140
|
+
|
|
141
|
+
const models = raw.data ?? raw.models ?? [];
|
|
142
|
+
return { count: raw.count ?? models.length, models };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async getPriceHistory(
|
|
146
|
+
query: GpuPriceHistoryQuery
|
|
147
|
+
): Promise<GpuPriceHistoryResponse> {
|
|
148
|
+
const model = query.model?.trim() ?? "";
|
|
149
|
+
if (!model) {
|
|
150
|
+
throw new TypeError("model is required for getPriceHistory()");
|
|
151
|
+
}
|
|
152
|
+
const params = new URLSearchParams();
|
|
153
|
+
params.set("model", model);
|
|
154
|
+
if (query.window) params.set("window", query.window);
|
|
155
|
+
if (query.interval) params.set("interval", query.interval);
|
|
156
|
+
if (query.category) params.set("category", query.category);
|
|
157
|
+
|
|
158
|
+
return this.requestJson<GpuPriceHistoryResponse>(
|
|
159
|
+
`/api/v1/agent/models/history?${params.toString()}`
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async calculateCost(input: AgentCalculateInput): Promise<{
|
|
164
|
+
read_only: boolean;
|
|
165
|
+
deterministic: boolean;
|
|
166
|
+
data: Record<string, unknown>;
|
|
167
|
+
}> {
|
|
168
|
+
return this.requestJson("/api/v1/agent/calculate", {
|
|
169
|
+
method: "POST",
|
|
170
|
+
body: input,
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async getProviderStatus(): Promise<{
|
|
175
|
+
caller_holder_tier?: HolderTierId;
|
|
176
|
+
ecosystem_token?: {
|
|
177
|
+
ticker: string;
|
|
178
|
+
contract_address: string;
|
|
179
|
+
decimals: number;
|
|
180
|
+
total_supply: number;
|
|
181
|
+
wallet_header: string;
|
|
182
|
+
};
|
|
183
|
+
summary: {
|
|
184
|
+
totalOffers: number;
|
|
185
|
+
filteredOffers?: number;
|
|
186
|
+
connectedProviders: number;
|
|
187
|
+
totalProviders: number;
|
|
188
|
+
lastSyncedAt: string | null;
|
|
189
|
+
};
|
|
190
|
+
providers: Array<{
|
|
191
|
+
provider: string;
|
|
192
|
+
status: string;
|
|
193
|
+
offerCount?: number;
|
|
194
|
+
offer_count?: number;
|
|
195
|
+
}>;
|
|
196
|
+
}> {
|
|
197
|
+
return this.requestJson("/api/v1/agent/status");
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async getTokenStanding(
|
|
201
|
+
address?: string,
|
|
202
|
+
options?: { refresh?: boolean }
|
|
203
|
+
): Promise<TokenStandingResponse> {
|
|
204
|
+
const target = (address ?? this.walletAddress ?? "").trim();
|
|
205
|
+
const params = new URLSearchParams();
|
|
206
|
+
if (target) {
|
|
207
|
+
if (!isValidEvmAddress(target)) {
|
|
208
|
+
throw new TypeError("Invalid 42-character EVM wallet address.");
|
|
209
|
+
}
|
|
210
|
+
params.set("address", target);
|
|
211
|
+
}
|
|
212
|
+
if (options?.refresh) {
|
|
213
|
+
params.set("refresh", "1");
|
|
214
|
+
}
|
|
215
|
+
const qs = params.toString();
|
|
216
|
+
return this.requestJson(`/api/token/standing${qs ? `?${qs}` : ""}`);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async compareLiveOffersForWorkload(params: {
|
|
220
|
+
workload: LlmSizingInput;
|
|
221
|
+
comparison: OfferTcoComparisonOptions;
|
|
222
|
+
query?: AgentOffersQuery;
|
|
223
|
+
}): Promise<{
|
|
224
|
+
sizing: LlmSizingResult;
|
|
225
|
+
comparison: OfferTcoComparisonResult;
|
|
226
|
+
}> {
|
|
227
|
+
const sizing = estimateLlmVramRequirements(params.workload);
|
|
228
|
+
const { offers } = await this.listOffers({
|
|
229
|
+
available_only: params.comparison.availableOnly ?? true,
|
|
230
|
+
limit: params.query?.limit ?? 100,
|
|
231
|
+
...params.query,
|
|
232
|
+
});
|
|
233
|
+
const comparison = rankOffersByTco(offers, {
|
|
234
|
+
...params.comparison,
|
|
235
|
+
minTotalVramGb:
|
|
236
|
+
params.comparison.minTotalVramGb ?? sizing.recommendedVramGb,
|
|
237
|
+
});
|
|
238
|
+
return { sizing, comparison };
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
private async requestJson<T>(
|
|
242
|
+
pathname: string,
|
|
243
|
+
init?: { method?: "GET" | "POST"; body?: unknown }
|
|
244
|
+
): Promise<T> {
|
|
245
|
+
const controller = new AbortController();
|
|
246
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
247
|
+
try {
|
|
248
|
+
const headers: Record<string, string> = {
|
|
249
|
+
Accept: "application/json",
|
|
250
|
+
};
|
|
251
|
+
if (this.walletAddress) {
|
|
252
|
+
headers["X-Latens-Wallet"] = this.walletAddress;
|
|
253
|
+
}
|
|
254
|
+
if (init?.body !== undefined) {
|
|
255
|
+
headers["Content-Type"] = "application/json";
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const res = await this.fetcher(`${this.baseUrl}${pathname}`, {
|
|
259
|
+
method: init?.method ?? "GET",
|
|
260
|
+
headers,
|
|
261
|
+
body: init?.body !== undefined ? JSON.stringify(init.body) : undefined,
|
|
262
|
+
signal: controller.signal,
|
|
263
|
+
});
|
|
264
|
+
if (!res.ok) {
|
|
265
|
+
throw new Error(`LATENS API HTTP ${res.status} on ${pathname}`);
|
|
266
|
+
}
|
|
267
|
+
return (await res.json()) as T;
|
|
268
|
+
} finally {
|
|
269
|
+
clearTimeout(timer);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
const MODEL_PATTERNS: Array<[RegExp, string]> = [
|
|
2
|
+
[/\bb200\b/i, "B200"],
|
|
3
|
+
[/\bgh200\b/i, "GH200"],
|
|
4
|
+
[/\bh200\b/i, "H200"],
|
|
5
|
+
[/\bh100\b.*\bsxm\b/i, "H100 SXM"],
|
|
6
|
+
[/\bh100\b.*\bpcie\b/i, "H100 PCIe"],
|
|
7
|
+
[/\bh100\b.*\bnvl\b/i, "H100 NVL"],
|
|
8
|
+
[/\bh100\b/i, "H100 SXM"],
|
|
9
|
+
[/\ba100\b.*\bsxm\b/i, "A100 SXM"],
|
|
10
|
+
[/\ba100\b.*\bpcie\b/i, "A100 PCIe"],
|
|
11
|
+
[/\ba100\b/i, "A100 SXM"],
|
|
12
|
+
[/\bmi300x\b/i, "MI300X"],
|
|
13
|
+
[/\bl40s\b/i, "L40S"],
|
|
14
|
+
[/\bl40\b/i, "L40"],
|
|
15
|
+
[/\brtx\s*6000\s*ada\b/i, "RTX 6000 Ada"],
|
|
16
|
+
[/\brtx\s*a6000\b/i, "RTX A6000"],
|
|
17
|
+
[/\brtx\s*5090\b/i, "RTX 5090"],
|
|
18
|
+
[/\brtx\s*4090\b/i, "RTX 4090"],
|
|
19
|
+
[/\brtx\s*3090\b/i, "RTX 3090"],
|
|
20
|
+
[/\ba40\b/i, "A40"],
|
|
21
|
+
[/\bl4\b/i, "L4"],
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
export function normalizeGpuModelName(rawName: string): string {
|
|
25
|
+
const cleaned = rawName
|
|
26
|
+
.replace(/^NVIDIA[\s_-]+/i, "")
|
|
27
|
+
.replace(/^AMD[\s_-]+/i, "")
|
|
28
|
+
.replace(/_/g, " ")
|
|
29
|
+
.replace(/\s+/g, " ")
|
|
30
|
+
.trim();
|
|
31
|
+
|
|
32
|
+
for (const [pattern, canonical] of MODEL_PATTERNS) {
|
|
33
|
+
if (pattern.test(cleaned)) {
|
|
34
|
+
return canonical;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return cleaned || "Unknown GPU";
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function roundUsd(value: number, decimals = 4): number {
|
|
41
|
+
const factor = 10 ** decimals;
|
|
42
|
+
return Math.round((value + Number.EPSILON) * factor) / factor;
|
|
43
|
+
}
|
package/src/sizing.ts
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
import { calculateDeterministicComputeCost } from "./calculator.js";
|
|
2
|
+
import { roundUsd } from "./normalizer.js";
|
|
3
|
+
import { calculateEffectiveDeskFeeBps } from "./standing.js";
|
|
4
|
+
import type {
|
|
5
|
+
HolderTierId,
|
|
6
|
+
LlmQuantization,
|
|
7
|
+
LlmSizingInput,
|
|
8
|
+
LlmSizingRecommendation,
|
|
9
|
+
LlmSizingResult,
|
|
10
|
+
NormalizedGpuOffer,
|
|
11
|
+
OfferTcoComparisonOptions,
|
|
12
|
+
OfferTcoComparisonResult,
|
|
13
|
+
RankedGpuOfferTco,
|
|
14
|
+
SettlementAsset,
|
|
15
|
+
} from "./types.js";
|
|
16
|
+
|
|
17
|
+
const BYTES_PER_PARAM: Record<LlmQuantization, number> = {
|
|
18
|
+
fp32: 4.0,
|
|
19
|
+
fp16: 2.0,
|
|
20
|
+
bf16: 2.0,
|
|
21
|
+
fp8: 1.0,
|
|
22
|
+
int8: 1.0,
|
|
23
|
+
q8_0: 1.06,
|
|
24
|
+
q4_k_m: 0.6,
|
|
25
|
+
int4: 0.55,
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const KV_BYTES_PER_ELEMENT: Record<"fp16" | "fp8" | "int8", number> = {
|
|
29
|
+
fp16: 2.0,
|
|
30
|
+
fp8: 1.0,
|
|
31
|
+
int8: 1.0,
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const HARDWARE_TEMPLATES: ReadonlyArray<{
|
|
35
|
+
gpuModel: string;
|
|
36
|
+
vramPerGpuGb: number;
|
|
37
|
+
validCounts: readonly number[];
|
|
38
|
+
notes: string;
|
|
39
|
+
}> = [
|
|
40
|
+
{
|
|
41
|
+
gpuModel: "RTX 3090",
|
|
42
|
+
vramPerGpuGb: 24,
|
|
43
|
+
validCounts: [1, 2, 4],
|
|
44
|
+
notes: "Cost-efficient 24 GB consumer tier for quantized inference.",
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
gpuModel: "RTX 4090",
|
|
48
|
+
vramPerGpuGb: 24,
|
|
49
|
+
validCounts: [1, 2, 4, 8],
|
|
50
|
+
notes: "High throughput 24 GB PCIe nodes for inference and LoRA fine-tuning.",
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
gpuModel: "L40S",
|
|
54
|
+
vramPerGpuGb: 48,
|
|
55
|
+
validCounts: [1, 2, 4, 8],
|
|
56
|
+
notes: "48 GB datacenter FP8 accelerator suited for mid-size LLMs.",
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
gpuModel: "A100 SXM",
|
|
60
|
+
vramPerGpuGb: 80,
|
|
61
|
+
validCounts: [1, 2, 4, 8],
|
|
62
|
+
notes: "80 GB HBM2e with NVLink for production inference and training.",
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
gpuModel: "H100 SXM",
|
|
66
|
+
vramPerGpuGb: 80,
|
|
67
|
+
validCounts: [1, 2, 4, 8],
|
|
68
|
+
notes: "80 GB HBM3 with Transformer Engine FP8 and high-bandwidth NVLink.",
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
gpuModel: "H200",
|
|
72
|
+
vramPerGpuGb: 141,
|
|
73
|
+
validCounts: [1, 2, 4, 8],
|
|
74
|
+
notes: "141 GB HBM3e for long-context 70B+ and 405B models with fewer nodes.",
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
gpuModel: "B200",
|
|
78
|
+
vramPerGpuGb: 192,
|
|
79
|
+
validCounts: [1, 2, 4, 8],
|
|
80
|
+
notes: "192 GB HBM3e flagship cluster nodes for frontier training and MoE.",
|
|
81
|
+
},
|
|
82
|
+
];
|
|
83
|
+
|
|
84
|
+
function estimateKvCacheGb(params: {
|
|
85
|
+
parameterCountBillions: number;
|
|
86
|
+
contextLength: number;
|
|
87
|
+
batchSize: number;
|
|
88
|
+
kvQuantization: "fp16" | "fp8" | "int8";
|
|
89
|
+
}): number {
|
|
90
|
+
const { parameterCountBillions, contextLength, batchSize, kvQuantization } =
|
|
91
|
+
params;
|
|
92
|
+
|
|
93
|
+
/*
|
|
94
|
+
* Deterministic GQA-aware heuristic matching modern Llama/Qwen/DeepSeek
|
|
95
|
+
* transformer architectures:
|
|
96
|
+
* - ~32 layers @ 7B, ~80 layers @ 70B, ~126 layers @ 405B
|
|
97
|
+
* - Effective KV heads/dim scales sublinearly with parameter count due to GQA
|
|
98
|
+
*/
|
|
99
|
+
const estimatedLayers = Math.max(
|
|
100
|
+
24,
|
|
101
|
+
Math.round(14 * Math.pow(parameterCountBillions, 0.42))
|
|
102
|
+
);
|
|
103
|
+
const kvHiddenDim = Math.max(
|
|
104
|
+
512,
|
|
105
|
+
Math.round(320 * Math.pow(parameterCountBillions, 0.34))
|
|
106
|
+
);
|
|
107
|
+
const bytesPerEl = KV_BYTES_PER_ELEMENT[kvQuantization];
|
|
108
|
+
const bytes =
|
|
109
|
+
2 * estimatedLayers * kvHiddenDim * contextLength * batchSize * bytesPerEl;
|
|
110
|
+
|
|
111
|
+
return bytes / 1024 ** 3;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Deterministically estimate GPU VRAM requirements for LLM inference,
|
|
116
|
+
* LoRA/QLoRA fine-tuning, or full-parameter fine-tuning, and return
|
|
117
|
+
* compatible multi-GPU hardware layouts.
|
|
118
|
+
*/
|
|
119
|
+
export function estimateLlmVramRequirements(
|
|
120
|
+
input: LlmSizingInput
|
|
121
|
+
): LlmSizingResult {
|
|
122
|
+
if (
|
|
123
|
+
!Number.isFinite(input.parameterCountBillions) ||
|
|
124
|
+
input.parameterCountBillions <= 0
|
|
125
|
+
) {
|
|
126
|
+
throw new RangeError("parameterCountBillions must be greater than zero.");
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const quantization: LlmQuantization = input.quantization ?? "bf16";
|
|
130
|
+
const mode = input.mode ?? "inference";
|
|
131
|
+
const contextLength = Math.max(512, Math.floor(input.contextLength ?? 8192));
|
|
132
|
+
const batchSize = Math.max(1, Math.floor(input.batchSize ?? 1));
|
|
133
|
+
const kvQuantization = input.kvCacheQuantization ?? "fp16";
|
|
134
|
+
const headroomPct = Math.min(50, Math.max(5, input.headroomPct ?? 15));
|
|
135
|
+
|
|
136
|
+
const bytesPerParam = BYTES_PER_PARAM[quantization];
|
|
137
|
+
if (!bytesPerParam) {
|
|
138
|
+
throw new TypeError(`Unsupported quantization: ${String(quantization)}`);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const weightsGb = (input.parameterCountBillions * 1e9 * bytesPerParam) / 1024 ** 3;
|
|
142
|
+
const kvCacheGb = estimateKvCacheGb({
|
|
143
|
+
parameterCountBillions: input.parameterCountBillions,
|
|
144
|
+
contextLength,
|
|
145
|
+
batchSize,
|
|
146
|
+
kvQuantization,
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
let trainingOverheadGb = 0;
|
|
150
|
+
if (mode === "lora_finetune") {
|
|
151
|
+
/* Adapter weights + AdamW states on trainable LoRA ranks + activation checkpoints */
|
|
152
|
+
const trainableParamRatio = 0.025;
|
|
153
|
+
const adapterStatesGb =
|
|
154
|
+
(input.parameterCountBillions * 1e9 * trainableParamRatio * 16) / 1024 ** 3;
|
|
155
|
+
const activationsGb =
|
|
156
|
+
(input.parameterCountBillions * 0.14 * Math.sqrt(contextLength / 4096)) *
|
|
157
|
+
Math.sqrt(batchSize);
|
|
158
|
+
trainingOverheadGb = adapterStatesGb + activationsGb;
|
|
159
|
+
} else if (mode === "full_finetune") {
|
|
160
|
+
/*
|
|
161
|
+
* Mixed-precision AdamW (FP32 master weights + momentum + variance = 12 bytes/param)
|
|
162
|
+
* plus BF16 gradients (2 bytes/param) and gradient-checkpointed activations.
|
|
163
|
+
*/
|
|
164
|
+
const optimizerAndGradsGb =
|
|
165
|
+
(input.parameterCountBillions * 1e9 * 14) / 1024 ** 3;
|
|
166
|
+
const activationsGb =
|
|
167
|
+
(input.parameterCountBillions * 0.25 * Math.sqrt(contextLength / 4096)) *
|
|
168
|
+
Math.sqrt(batchSize);
|
|
169
|
+
trainingOverheadGb = optimizerAndGradsGb + activationsGb;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const cudaContextGb = 1.5;
|
|
173
|
+
const rawTotalGb = weightsGb + kvCacheGb + trainingOverheadGb + cudaContextGb;
|
|
174
|
+
const runtimeOverheadGb = cudaContextGb + rawTotalGb * (headroomPct / 100);
|
|
175
|
+
const minimumVramGb = roundUsd(rawTotalGb, 2);
|
|
176
|
+
const recommendedVramGb = roundUsd(
|
|
177
|
+
weightsGb + kvCacheGb + trainingOverheadGb + runtimeOverheadGb,
|
|
178
|
+
2
|
|
179
|
+
);
|
|
180
|
+
|
|
181
|
+
const recommendedConfigs: LlmSizingRecommendation[] = [];
|
|
182
|
+
for (const tpl of HARDWARE_TEMPLATES) {
|
|
183
|
+
const count = tpl.validCounts.find(
|
|
184
|
+
(c) => c * tpl.vramPerGpuGb >= recommendedVramGb
|
|
185
|
+
);
|
|
186
|
+
if (!count) continue;
|
|
187
|
+
const totalVramGb = count * tpl.vramPerGpuGb;
|
|
188
|
+
const utilizationPct = roundUsd((recommendedVramGb / totalVramGb) * 100, 1);
|
|
189
|
+
recommendedConfigs.push({
|
|
190
|
+
gpuModel: tpl.gpuModel,
|
|
191
|
+
gpuCount: count,
|
|
192
|
+
vramPerGpuGb: tpl.vramPerGpuGb,
|
|
193
|
+
totalVramGb,
|
|
194
|
+
estimatedUtilizationPct: utilizationPct,
|
|
195
|
+
notes: tpl.notes,
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
recommendedConfigs.sort((a, b) => {
|
|
200
|
+
if (a.gpuCount !== b.gpuCount) return a.gpuCount - b.gpuCount;
|
|
201
|
+
return a.totalVramGb - b.totalVramGb;
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
return {
|
|
205
|
+
parameterCountBillions: input.parameterCountBillions,
|
|
206
|
+
quantization,
|
|
207
|
+
mode,
|
|
208
|
+
contextLength,
|
|
209
|
+
batchSize,
|
|
210
|
+
kvCacheQuantization: kvQuantization,
|
|
211
|
+
weightsGb: roundUsd(weightsGb, 2),
|
|
212
|
+
kvCacheGb: roundUsd(kvCacheGb, 2),
|
|
213
|
+
trainingOverheadGb: roundUsd(trainingOverheadGb, 2),
|
|
214
|
+
runtimeOverheadGb: roundUsd(runtimeOverheadGb, 2),
|
|
215
|
+
minimumVramGb,
|
|
216
|
+
recommendedVramGb,
|
|
217
|
+
recommendedConfigs,
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Deterministically rank normalized GPU offers by total cost of ownership
|
|
223
|
+
* (compute + persistent storage + outbound egress), with optional $LTNS
|
|
224
|
+
* Private Compute Desk fee estimation.
|
|
225
|
+
*/
|
|
226
|
+
export function rankOffersByTco(
|
|
227
|
+
offers: readonly NormalizedGpuOffer[],
|
|
228
|
+
options: OfferTcoComparisonOptions
|
|
229
|
+
): OfferTcoComparisonResult {
|
|
230
|
+
if (!Number.isFinite(options.durationHours) || options.durationHours <= 0) {
|
|
231
|
+
throw new RangeError("durationHours must be greater than zero.");
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const availableOnly = options.availableOnly ?? true;
|
|
235
|
+
const confirmedOnly = options.confirmedOnly ?? false;
|
|
236
|
+
const minTotalVramGb = Math.max(0, options.minTotalVramGb ?? 0);
|
|
237
|
+
const storageGb = Math.max(0, options.storageGb ?? 0);
|
|
238
|
+
const egressGb = Math.max(0, options.egressGb ?? 0);
|
|
239
|
+
const fallbackStorageRate = Math.max(
|
|
240
|
+
0,
|
|
241
|
+
options.defaultStorageCostPerGbMonthUsd ?? 0.1
|
|
242
|
+
);
|
|
243
|
+
const fallbackEgressRate = Math.max(0, options.defaultEgressCostPerGbUsd ?? 0);
|
|
244
|
+
const holderTier: HolderTierId = options.holderTier ?? "open";
|
|
245
|
+
const settlementAsset: SettlementAsset = options.settlementAsset ?? "USDG";
|
|
246
|
+
|
|
247
|
+
const feeSpec = calculateEffectiveDeskFeeBps(holderTier, settlementAsset);
|
|
248
|
+
|
|
249
|
+
const eligible = offers.filter((offer) => {
|
|
250
|
+
if (availableOnly && offer.availability_status === "unavailable") {
|
|
251
|
+
return false;
|
|
252
|
+
}
|
|
253
|
+
if (confirmedOnly && offer.price_precision !== "confirmed_offer") {
|
|
254
|
+
return false;
|
|
255
|
+
}
|
|
256
|
+
if (offer.total_vram_gb < minTotalVramGb) {
|
|
257
|
+
return false;
|
|
258
|
+
}
|
|
259
|
+
return offer.hourly_price_usd > 0;
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
const rankedRaw: RankedGpuOfferTco[] = eligible.map((offer) => {
|
|
263
|
+
const breakdown = calculateDeterministicComputeCost({
|
|
264
|
+
hourlyRatePerInstanceUsd: offer.hourly_price_usd,
|
|
265
|
+
instanceCount: 1,
|
|
266
|
+
durationHours: options.durationHours,
|
|
267
|
+
storageGb,
|
|
268
|
+
storageCostPerGbMonthUsd:
|
|
269
|
+
offer.storage_cost_per_gb_month_usd ?? fallbackStorageRate,
|
|
270
|
+
egressGb,
|
|
271
|
+
egressCostPerGbUsd: offer.egress_cost_per_gb_usd ?? fallbackEgressRate,
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
const estimatedDeskFeeUsd = roundUsd(
|
|
275
|
+
breakdown.totalEstimatedUsd * (feeSpec.effectiveFeeBps / 10_000),
|
|
276
|
+
4
|
|
277
|
+
);
|
|
278
|
+
|
|
279
|
+
return {
|
|
280
|
+
offerId: offer.id,
|
|
281
|
+
provider: offer.provider,
|
|
282
|
+
gpuModel: offer.gpu_model,
|
|
283
|
+
gpuCount: offer.gpu_count,
|
|
284
|
+
totalVramGb: offer.total_vram_gb,
|
|
285
|
+
region: offer.region,
|
|
286
|
+
pricePrecision: offer.price_precision,
|
|
287
|
+
productCategory: offer.product_category,
|
|
288
|
+
hourlyPriceUsd: roundUsd(offer.hourly_price_usd, 4),
|
|
289
|
+
pricePerGpuUsd: roundUsd(offer.price_per_gpu_usd, 4),
|
|
290
|
+
breakdown,
|
|
291
|
+
deskFeeBps: feeSpec.effectiveFeeBps,
|
|
292
|
+
estimatedDeskFeeUsd,
|
|
293
|
+
totalWithDeskFeeUsd: roundUsd(
|
|
294
|
+
breakdown.totalEstimatedUsd + estimatedDeskFeeUsd,
|
|
295
|
+
4
|
|
296
|
+
),
|
|
297
|
+
savingsVsMostExpensiveUsd: 0,
|
|
298
|
+
sourceUrl: offer.source_url,
|
|
299
|
+
};
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
rankedRaw.sort(
|
|
303
|
+
(a, b) => a.breakdown.totalEstimatedUsd - b.breakdown.totalEstimatedUsd
|
|
304
|
+
);
|
|
305
|
+
|
|
306
|
+
const cheapest = rankedRaw[0]?.breakdown.totalEstimatedUsd ?? 0;
|
|
307
|
+
const mostExpensive =
|
|
308
|
+
rankedRaw[rankedRaw.length - 1]?.breakdown.totalEstimatedUsd ?? 0;
|
|
309
|
+
|
|
310
|
+
const ranked = rankedRaw.map((entry) => ({
|
|
311
|
+
...entry,
|
|
312
|
+
savingsVsMostExpensiveUsd: roundUsd(
|
|
313
|
+
Math.max(0, mostExpensive - entry.breakdown.totalEstimatedUsd),
|
|
314
|
+
4
|
|
315
|
+
),
|
|
316
|
+
}));
|
|
317
|
+
|
|
318
|
+
const spreadMultiplier =
|
|
319
|
+
cheapest > 0 && mostExpensive > 0
|
|
320
|
+
? roundUsd(mostExpensive / cheapest, 2)
|
|
321
|
+
: 1;
|
|
322
|
+
|
|
323
|
+
return {
|
|
324
|
+
durationHours: options.durationHours,
|
|
325
|
+
evaluatedCount: offers.length,
|
|
326
|
+
eligibleCount: ranked.length,
|
|
327
|
+
holderTier,
|
|
328
|
+
settlementAsset,
|
|
329
|
+
effectiveDeskFeeBps: feeSpec.effectiveFeeBps,
|
|
330
|
+
cheapestTotalUsd: cheapest,
|
|
331
|
+
mostExpensiveTotalUsd: mostExpensive,
|
|
332
|
+
spreadMultiplier,
|
|
333
|
+
ranked,
|
|
334
|
+
};
|
|
335
|
+
}
|