@margoengine/compute 0.0.0-stage → 0.1.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.
Files changed (71) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +736 -3
  4. package/dist/array-DbI848Wf.js +166 -0
  5. package/dist/array.d.ts +109 -0
  6. package/dist/autodiff.d.ts +22 -0
  7. package/dist/autodiff.js +143 -0
  8. package/dist/autotune.d.ts +100 -0
  9. package/dist/autotune.js +179 -0
  10. package/dist/compat-YK57ZCbA.js +4 -0
  11. package/dist/compat.d.ts +2 -0
  12. package/dist/context-C75sQQra.js +2470 -0
  13. package/dist/context.d.ts +368 -0
  14. package/dist/cpu-CdVdqP4I.js +871 -0
  15. package/dist/cpu-kernel.wasm +0 -0
  16. package/dist/cpu-load-aTmfphVu.js +5 -0
  17. package/dist/cpu-load.d.ts +3 -0
  18. package/dist/cpu-runtime.d.ts +8 -0
  19. package/dist/cpu-wasm.d.ts +42 -0
  20. package/dist/cpu-wasm.js +161 -0
  21. package/dist/cpu.d.ts +138 -0
  22. package/dist/decomp-kernel.wasm +0 -0
  23. package/dist/decomp.d.ts +42 -0
  24. package/dist/decomp.js +158 -0
  25. package/dist/distance.d.ts +85 -0
  26. package/dist/distance.js +256 -0
  27. package/dist/dtype.d.ts +36 -0
  28. package/dist/errors-CDgOgzCd.js +7 -0
  29. package/dist/expr-DwFen60A.js +995 -0
  30. package/dist/expr.d.ts +196 -0
  31. package/dist/fft.d.ts +33 -0
  32. package/dist/fft.js +168 -0
  33. package/dist/frame.d.ts +63 -0
  34. package/dist/frame.js +82 -0
  35. package/dist/graph.d.ts +75 -0
  36. package/dist/graph.js +174 -0
  37. package/dist/histogram.d.ts +17 -0
  38. package/dist/index.d.ts +17 -0
  39. package/dist/index.js +4 -0
  40. package/dist/kernel.d.ts +65 -0
  41. package/dist/linalg.d.ts +21 -0
  42. package/dist/linalg.js +149 -0
  43. package/dist/nn-extra.d.ts +130 -0
  44. package/dist/nn-extra.js +322 -0
  45. package/dist/nn.d.ts +385 -0
  46. package/dist/nn.js +704 -0
  47. package/dist/onnx-kernel.wasm +0 -0
  48. package/dist/onnx.d.ts +164 -0
  49. package/dist/onnx.js +817 -0
  50. package/dist/quant.d.ts +59 -0
  51. package/dist/quant.js +242 -0
  52. package/dist/random.d.ts +64 -0
  53. package/dist/random.js +150 -0
  54. package/dist/reduce.d.ts +34 -0
  55. package/dist/scan.d.ts +26 -0
  56. package/dist/select.d.ts +38 -0
  57. package/dist/shaders.d.ts +80 -0
  58. package/dist/shape.d.ts +23 -0
  59. package/dist/shape.js +134 -0
  60. package/dist/signal.d.ts +29 -0
  61. package/dist/signal.js +178 -0
  62. package/dist/sort.d.ts +38 -0
  63. package/dist/sparse.d.ts +136 -0
  64. package/dist/sparse.js +273 -0
  65. package/dist/stream.d.ts +39 -0
  66. package/dist/stream.js +100 -0
  67. package/dist/subgroups.d.ts +27 -0
  68. package/dist/subgroups.js +191 -0
  69. package/dist/usingCtx-igdMnAhr.js +57 -0
  70. package/dist/wgsl.d.ts +68 -0
  71. package/package.json +144 -6
@@ -0,0 +1,368 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ // @ts-ignore optional peer: its types apply when it is installed
3
+ import type { EngineKernel } from '@margoengine/core';
4
+ import { GpuArray } from './array.js';
5
+ import { type DType } from './dtype.js';
6
+ import { Expr, Operand, type AxisOptions, type OperandLike } from './expr.js';
7
+ import { type BindingInfo, type HostValue, type ModuleInfo } from './wgsl.js';
8
+ import { type KernelRoute, type Operator } from './shaders.js';
9
+ import * as scan from './scan.js';
10
+ import * as sort from './sort.js';
11
+ import * as select from './select.js';
12
+ import { type Histogram, type HistogramOptions } from './histogram.js';
13
+ import { Kernel } from './kernel.js';
14
+ /** @internal Refuses a tuning table this device cannot run. */
15
+ export declare function checkTuning(table: ComputeTuning, limit: number): void;
16
+ /** Options for {@link createCompute}. */
17
+ export interface CreateComputeOptions {
18
+ /** Reuse this engine's GPU device (WebGPU backend). Default: a headless device of the context's own. */
19
+ readonly engine?: EngineKernel;
20
+ /** Reuse this GPU device. Takes precedence over `engine`. */
21
+ readonly device?: GPUDevice;
22
+ /** Adapter choice for a device of the context's own. Default `'high-performance'`, except on Windows where browsers ignore it (and warn), so none is sent. */
23
+ readonly powerPreference?: GPUPowerPreference;
24
+ /** Abandons device creation: the promise rejects with the signal's reason. */
25
+ readonly signal?: AbortSignal;
26
+ /**
27
+ * Where the work runs. `'auto'` (default): WebGPU when the runtime has a usable adapter, otherwise the CPU.
28
+ * `'webgpu'`: WebGPU or reject (MargoError `unsupported`). `'cpu'`: always the CPU, in JavaScript on the calling
29
+ * thread, with the same API except your own WGSL (`kernel`, `map`, custom operators). Ignored with `device` or
30
+ * `engine`, which are WebGPU.
31
+ */
32
+ readonly backend?: 'auto' | 'webgpu' | 'cpu';
33
+ /**
34
+ * Use the WGSL builtins for `sin`, `exp`, `pow` and the other transcendental functions. Default `false`: precise
35
+ * f32 versions within 1-2.5 ulp (pow up to 5) that give the same results on every GPU. The builtins are faster but
36
+ * only as accurate as the WGSL specification asks (sin and cos 2^-11 absolute in [-pi, pi], atan2 4096 ulp, pow
37
+ * undefined for negative bases) and differ from GPU to GPU. The CPU backend ignores it.
38
+ */
39
+ readonly fastMath?: boolean;
40
+ /**
41
+ * Threads per workgroup for the context's own `reduce`, `scan` and `sort` kernels, usually what `tuneCompute` from
42
+ * `@margoengine/compute/autotune` measured. Each is 64, 128, 256, 512 or 1024 and within the device's limit. Default
43
+ * 256 for all three. Integer results and sort orders stay the same; float sums round in another order. The CPU
44
+ * backend, `useSubgroups` and the WebGL2 layer's sort use their own kernels and ignore it.
45
+ */
46
+ readonly tuned?: ComputeTuning;
47
+ }
48
+ /** Threads per workgroup of the context's own kernels. See {@link CreateComputeOptions.tuned}. */
49
+ export interface ComputeTuning {
50
+ /** Full reductions: `sum`, `min`, `max`, and whatever is built on them. */
51
+ readonly reduce?: number;
52
+ /** Flat scans: `cumsum` and whatever is built on it. */
53
+ readonly scan?: number;
54
+ /** Radix sorts: `sort`, `argsort`, `sortByKey`. */
55
+ readonly sort?: number;
56
+ }
57
+ /** Waiting options: an AbortSignal. */
58
+ export interface WaitOptions {
59
+ /** Abandons the wait: the promise rejects with the signal's reason. */
60
+ readonly signal?: AbortSignal;
61
+ }
62
+ /** Options for creating arrays: element type and shape. */
63
+ export interface ArrayOptions<T extends DType = DType> {
64
+ /** Element type. Default from the data's TypedArray, else `'f32'`. */
65
+ readonly dtype?: T;
66
+ /** Shape. Default `[data.length]`. */
67
+ readonly shape?: readonly number[];
68
+ }
69
+ /** A resource a kernel binding accepts by name. */
70
+ export type BindingResource = GpuArray | GPUBuffer | GPUBufferBinding | GPUTexture | GPUTextureView | GPUSampler | ArrayBufferView | HostValue;
71
+ /** GPU time of one pass, from `profile()`. */
72
+ export interface PassTiming {
73
+ /** What ran: `eval`, `reduce`, `sort.local`, a kernel's entry point, ... */
74
+ readonly label: string;
75
+ /** GPU milliseconds between the pass's start and end timestamps. */
76
+ readonly ms: number;
77
+ }
78
+ /** @internal A compiled program. */
79
+ export interface Program {
80
+ readonly pipeline: GPUComputePipeline;
81
+ readonly layouts: GPUBindGroupLayout[];
82
+ readonly info: ModuleInfo;
83
+ readonly entry: ModuleInfo['entryPoints'][number];
84
+ readonly label: string;
85
+ }
86
+ /** @internal One dispatch: a program, its resources by binding name, and workgroups (or an indirect buffer). */
87
+ export interface Pass {
88
+ readonly program: Program;
89
+ readonly resources: Readonly<Record<string, BindingResource>>;
90
+ readonly workgroups?: readonly [number, number, number];
91
+ readonly indirect?: {
92
+ readonly buffer: GPUBuffer;
93
+ readonly offset: number;
94
+ };
95
+ }
96
+ /** @internal A buffer-to-buffer copy queued after the passes. */
97
+ export type Copy = readonly [GPUBuffer, number, GPUBuffer, number, number];
98
+ /** Throws the signal's reason when it has aborted. */
99
+ export declare const aborted: (signal: AbortSignal | undefined) => void;
100
+ /**
101
+ * GPU compute without the WebGPU boilerplate, NumPy style: N-dimensional typed arrays with views and broadcasting,
102
+ * fused element-wise expressions, reductions along axes, statistics, scans, sorting, selection, histograms, and your
103
+ * own WGSL kernels bound by name. More lives in tree-shakable entries: `@margoengine/compute/linalg` (matmul),
104
+ * `/fft`, `/signal` (convolution), `/random` (counter-based RNG), `/stream` (data larger than GPU memory) and `/frame`
105
+ * (kernels in an engine's frame). Create a context with {@link createCompute}; dispose it (`using gpu = await
106
+ * createCompute()`) to free every array it made and, when it opened its own device, the device.
107
+ *
108
+ * Operations queue GPU work and return at once; anything that waits (`read`, `item`, `done`, `profile`) takes an
109
+ * AbortSignal and rejects with a MargoError (`failed`) carrying the GPU's message when queued work failed (a WGSL
110
+ * error in a kernel or expression, out of memory).
111
+ */
112
+ export declare class ComputeContext {
113
+ #private;
114
+ /** The GPU device the context runs on. */
115
+ readonly device: GPUDevice;
116
+ /** True when the context opened the device itself (and destroys it on dispose). */
117
+ readonly ownsDevice: boolean;
118
+ /** Resolves when the device is lost (also after an owned device is destroyed by dispose). */
119
+ readonly lost: Promise<GPUDeviceLostInfo>;
120
+ /** True when element-wise functions use the WGSL builtins (`createCompute({ fastMath })`). */
121
+ readonly fastMath: boolean;
122
+ /** Threads per workgroup of the context's own kernels. `tuneCompute` sets it, and so does `createCompute({ tuned })`. */
123
+ tuned: ComputeTuning;
124
+ /** @internal The sort kernel of the WebGL2 layer's route (./compat.ts), once loaded; only on the layer. */
125
+ sortRoute: string | undefined;
126
+ /** @internal Kernels of an optional entry (`/subgroups`) in place of the default ones. */
127
+ kernelRoute: KernelRoute | undefined;
128
+ /** @internal Resolves once the layer's route has loaded (at once on native WebGPU). */
129
+ readonly routeReady: Promise<void>;
130
+ /** @internal Use {@link createCompute}. */
131
+ constructor(device: GPUDevice, ownsDevice: boolean, fastMath?: boolean);
132
+ /** True after `dispose()`. */
133
+ get disposed(): boolean;
134
+ /** Where the work runs: `'webgpu'`, or `'cpu'` for the fallback (`createCompute({ backend })`). */
135
+ get backend(): 'webgpu' | 'cpu';
136
+ /** True when the device can run `f16` arrays (the `shader-f16` feature). */
137
+ get f16(): boolean;
138
+ /** True when the device has the `subgroups` feature, which `@margoengine/compute/subgroups` puts to use. */
139
+ get subgroups(): boolean;
140
+ /** @internal Throws after dispose. */
141
+ check(): void;
142
+ /** @internal A zero-filled buffer of `size` bytes for an array of `dtype`: STORAGE, COPY_SRC, COPY_DST and `usage`. */
143
+ allocate(size: number, usage: number, _dtype: DType): GPUBuffer;
144
+ /** @internal An array of `shape`, zero-filled (WebGPU clears new buffers), with extra buffer `usage` flags. */
145
+ empty<T extends DType>(shape: readonly number[], dtype: T, usage?: number): GpuArray<T>;
146
+ /**
147
+ * A GPU array from data: a TypedArray (its type picks the dtype: floats `f32`, Float16Array `f16`, signed `i32`,
148
+ * unsigned `u32`; Float64Array is converted to f32) or a plain array (`f32` unless `dtype` says otherwise), shaped
149
+ * `shape` (default flat). The second argument may be just the dtype.
150
+ * @example const m = gpu.array(new Float32Array(6), { shape: [2, 3] }); const u = gpu.array([1, 2, 3], 'u32');
151
+ */
152
+ array<T extends DType = 'f32'>(data: ArrayLike<number> | ArrayBufferView, options?: ArrayOptions<T> | T): GpuArray<T>;
153
+ /**
154
+ * A u32 array of `[x, y, z]` workgroup counts usable as an indirect dispatch argument (`kernel.run({ indirect })`),
155
+ * which a GPU pass can fill (from a compaction's count, say) without a round trip to the CPU.
156
+ */
157
+ indirectArgs(workgroups?: readonly [number, number, number]): GpuArray<'u32'>;
158
+ /**
159
+ * An array whose buffer can also feed draws (VERTEX and INDIRECT usage), for compute results the engine draws
160
+ * straight from: particle positions, culled instance lists, indirect draw arguments.
161
+ */
162
+ drawable<T extends DType = 'f32'>(shape: number | readonly number[], dtype?: T): GpuArray<T>;
163
+ /** Zeros of `shape` (a number for 1D). */
164
+ zeros<T extends DType = 'f32'>(shape: number | readonly number[], dtype?: T): GpuArray<T>;
165
+ /** Ones of `shape`. */
166
+ ones<T extends DType = 'f32'>(shape: number | readonly number[], dtype?: T): GpuArray<T>;
167
+ /** `value` everywhere in `shape`. */
168
+ full<T extends DType = 'f32'>(shape: number | readonly number[], value: number, dtype?: T): GpuArray<T>;
169
+ /** Evenly spaced values in [start, stop) by `step` (NumPy `arange`; `arange(5)` is 0..4, as u32). */
170
+ arange<T extends DType = DType>(start: number, stop?: number, step?: number, dtype?: T): GpuArray<T>;
171
+ /** `num` evenly spaced values from start to stop inclusive (NumPy `linspace`), f32. */
172
+ linspace(start: number, stop: number, num?: number): GpuArray<'f32'>;
173
+ /** The `n` x `n` identity matrix. */
174
+ eye<T extends DType = 'f32'>(n: number, dtype?: T): GpuArray<T>;
175
+ /** NumPy `where(condition, a, b)`: a lazy expression taking `a` where the condition is non-zero, else `b`. */
176
+ where(condition: Operand, a: OperandLike, b: OperandLike): Expr;
177
+ /** @internal Called by GpuArray.dispose. */
178
+ forget(array: GpuArray): void;
179
+ /** @internal Registers an owning array for disposal with the context. */
180
+ track(array: GpuArray): void;
181
+ /** @internal Runs an expression (or copies a view) into a new contiguous array. */
182
+ evaluate(operand: Operand): GpuArray;
183
+ /** @internal Storage buffers a fused read may use, leaving `reserved` for the kernel's own buffers. */
184
+ maxStorage(reserved: number): number;
185
+ /** @internal Writes bytes at an offset that is not 4-byte aligned (f16 runs) through a word-masking kernel. */
186
+ writeUnaligned(buffer: GPUBuffer, at: number, bytes: Uint8Array): void;
187
+ /**
188
+ * Compiles a WGSL compute kernel. Its `@group @binding` resources are read from the source and bound by name, so no
189
+ * bind group or pipeline layouts are written by hand. `entryPoint` picks one of several `@compute` functions; `label`
190
+ * names the pipeline in GPU errors and `profile()` (default the entry point). WGSL errors are reported by the next
191
+ * wait (`read`, `done`) as a MargoError (`failed`).
192
+ */
193
+ kernel(code: string, options?: {
194
+ readonly entryPoint?: string;
195
+ readonly label?: string;
196
+ }): Kernel;
197
+ /** @internal A compiled program, cached by source and entry point (least recently used out past 512). */
198
+ program(code: string, entryPoint?: string, label?: string): Program;
199
+ /** @internal Runs `work` inside validation, out-of-memory and internal error scopes, reported by the next wait. */
200
+ scoped<T>(work: () => T): T;
201
+ /** @internal Bind groups for a pass; buffers made for plain values go to `temporary`. */
202
+ bindGroups(program: Program, resources: Readonly<Record<string, BindingResource>>, temporary: GPUBuffer[]): GPUBindGroup[];
203
+ /** @internal Encodes passes into `encoder` (with timestamps while profiling); returns the temporary buffers. */
204
+ encode(encoder: GPUCommandEncoder, passes: readonly Pass[]): GPUBuffer[];
205
+ /** @internal Encodes and submits passes in one command buffer, then queued copies. */
206
+ submit(passes: readonly Pass[], copies?: readonly Copy[]): void;
207
+ /** @internal The binding resource for one declared binding. */
208
+ resource(b: BindingInfo, value: BindingResource | undefined, temporary: GPUBuffer[]): GPUBindingResource;
209
+ /** @internal Bytes for a uniform or read-only storage binding given as a TypedArray or a plain value. */
210
+ bytesFor(b: BindingInfo, value: BindingResource): Uint8Array<ArrayBuffer>;
211
+ /** @internal Workgroups for `groups` 1D workgroups, folded into a 2D grid past the per-dimension limit. */
212
+ grid(groups: number): [number, number, number];
213
+ /** @internal Reads bytes of a buffer once queued work is done; rejects on GPU errors, abort or disposal. */
214
+ readBytes(buffer: GPUBuffer, offset: number, size: number, signal?: AbortSignal): Promise<ArrayBuffer>;
215
+ /** Resolves when every queued operation has finished on the GPU; rejects like `read` when one failed. */
216
+ done(options?: WaitOptions): Promise<void>;
217
+ /**
218
+ * Runs `work` and resolves the GPU time of every pass it queued, measured with timestamp queries. Resolves an
219
+ * empty list on a device without the `timestamp-query` feature.
220
+ * @example const timings = await gpu.profile(() => gpu.sort(keys)); // [{ label: 'sort.local', ms: 0.12 }, ...]
221
+ */
222
+ profile(work: () => unknown, options?: WaitOptions): Promise<PassTiming[]>;
223
+ /**
224
+ * Element-wise map with a WGSL expression: one input is named `x`, several are passed as an object and named by
225
+ * their keys; `i` is the flat index and `n` the size. An expression containing `return` is a function body. The
226
+ * inputs share one shape. `dtype` is the output type, default the first input's; `label` names the pass (default
227
+ * `'map'`). (Element-wise methods such as
228
+ * `x.mul(2).add(1)` fuse the same way without WGSL.)
229
+ * @example const y = gpu.map(x, 'x * x + 1.0'); const d = gpu.map({ a, b }, 'abs(a - b)');
230
+ */
231
+ map<T extends DType = DType>(inputs: Operand | Readonly<Record<string, Operand>>, expression: string, options?: {
232
+ readonly dtype?: T;
233
+ readonly label?: string;
234
+ }): GpuArray<T>;
235
+ /**
236
+ * Folds elements with `op` (`'sum'`, `'product'`, `'min'`, `'max'`, or WGSL `{ combine: 'a + b', identity: '0.0' }`)
237
+ * over every element or along `axis`, fused with the expression it reads. Returns an array (shape `[]` for a full
238
+ * reduction; `await r.item()` reads the value). Integer sums wrap at 32 bits.
239
+ */
240
+ reduce(input: Operand, op?: Operator, options?: AxisOptions): GpuArray;
241
+ /** Sum (NumPy `sum`). */ sum(input: Operand, options?: AxisOptions): GpuArray;
242
+ /** Product. */ prod(input: Operand, options?: AxisOptions): GpuArray;
243
+ /** Minimum. */ min(input: Operand, options?: AxisOptions): GpuArray;
244
+ /** Maximum. */ max(input: Operand, options?: AxisOptions): GpuArray;
245
+ /** Mean, in f32. */ mean(input: Operand, options?: AxisOptions): GpuArray;
246
+ /** Variance with `ddof` (default 0), in f32, in two passes (mean, then squared deviations). */
247
+ var(input: Operand, options?: AxisOptions & {
248
+ readonly ddof?: number;
249
+ }): GpuArray;
250
+ /** Standard deviation with `ddof` (default 0), in f32. */
251
+ std(input: Operand, options?: AxisOptions & {
252
+ readonly ddof?: number;
253
+ }): GpuArray;
254
+ /** Index of the minimum (first on ties), flat or along one axis. */
255
+ argmin(input: Operand, options?: {
256
+ readonly axis?: number;
257
+ readonly keepdims?: boolean;
258
+ }): GpuArray<'u32'>;
259
+ /** Index of the maximum (first on ties), flat or along one axis. */
260
+ argmax(input: Operand, options?: {
261
+ readonly axis?: number;
262
+ readonly keepdims?: boolean;
263
+ }): GpuArray<'u32'>;
264
+ /** 1 when every element is non-zero (u32). */ all(input: Operand, options?: AxisOptions): GpuArray;
265
+ /** 1 when any element is non-zero (u32). */ any(input: Operand, options?: AxisOptions): GpuArray;
266
+ /** Number of non-zero elements (u32). */ countNonzero(input: Operand, options?: AxisOptions): GpuArray;
267
+ /** Sum ignoring NaN. */ nansum(input: Operand, options?: AxisOptions): GpuArray;
268
+ /** Minimum ignoring NaN (+Infinity when every element is NaN). */ nanmin(input: Operand, options?: AxisOptions): GpuArray;
269
+ /** Maximum ignoring NaN (-Infinity when every element is NaN). */ nanmax(input: Operand, options?: AxisOptions): GpuArray;
270
+ /** Mean ignoring NaN, in f32. */ nanmean(input: Operand, options?: AxisOptions): GpuArray;
271
+ /**
272
+ * Prefix scan with `op` (default sum): element i combines elements 0..i (inclusive, the default) or 0..i-1
273
+ * (`exclusive`), over the flat array or along `axis` (each line on its own). `scan(a)` is NumPy's `cumsum`.
274
+ */
275
+ scan(input: Operand, options?: scan.ScanOptions): GpuArray;
276
+ /** Inclusive sum along `axis` (default flat), NumPy `cumsum`. */
277
+ cumsum(input: Operand, options?: {
278
+ readonly axis?: number;
279
+ }): GpuArray;
280
+ /** Inclusive product along `axis`, NumPy `cumprod`. */
281
+ cumprod(input: Operand, options?: {
282
+ readonly axis?: number;
283
+ }): GpuArray;
284
+ /** Scan restarting where `flags` is non-zero (a new segment starts at that element). Inclusive unless `exclusive`. */
285
+ segmentedScan(values: Operand, flags: Operand, options?: Omit<scan.ScanOptions, 'axis'>): GpuArray;
286
+ /**
287
+ * Group-by on runs of equal consecutive keys (sort first to group all equal keys): resolves the distinct keys and
288
+ * each run's values folded with `op` (default sum).
289
+ */
290
+ reduceByKey(keys: Operand, values: Operand, options?: {
291
+ readonly op?: Operator;
292
+ } & WaitOptions): Promise<{
293
+ keys: GpuArray;
294
+ values: GpuArray;
295
+ }>;
296
+ /** A sorted copy of the flat elements (ascending, or `descending`), stable. Floats: -Infinity first, NaN by sign bit. */
297
+ sort(input: Operand, options?: sort.SortOptions): GpuArray;
298
+ /** The flat indices that sort the input (u32), stable, like NumPy's `argsort`. */
299
+ argsort(input: Operand, options?: sort.SortOptions): GpuArray<'u32'>;
300
+ /** Sorts `keys` and moves `values` (any type, same size) with them. Returns new arrays. */
301
+ sortByKey(keys: Operand, values: Operand, options?: sort.SortOptions): {
302
+ readonly keys: GpuArray;
303
+ readonly values: GpuArray;
304
+ };
305
+ /** The `k` largest (or with `largest: false`, smallest) values and their flat indices, in order. */
306
+ topk(input: Operand, k: number, options?: {
307
+ readonly largest?: boolean;
308
+ }): {
309
+ readonly values: GpuArray;
310
+ readonly indices: GpuArray<'u32'>;
311
+ };
312
+ /** Quantiles `q` in [0, 1] (a number, or a list for several) with NumPy's default linear interpolation, f32. */
313
+ quantile(input: Operand, q: number | readonly number[]): GpuArray<'f32'>;
314
+ /** Median (the 0.5 quantile), f32, shape `[]`. */
315
+ median(input: Operand): GpuArray<'f32'>;
316
+ /** The distinct values in ascending order, and with `counts: true` how often each occurs. Reads the count back. */
317
+ unique(input: Operand, options?: {
318
+ readonly counts?: boolean;
319
+ } & WaitOptions): Promise<{
320
+ values: GpuArray;
321
+ counts?: GpuArray<'u32'>;
322
+ }>;
323
+ /** Elements at `indices` (flat, or along `axis`), NumPy `take`; out-of-range indices clip (or `mode: 'wrap'`). */
324
+ take(input: Operand, indices: Operand, options?: select.TakeOptions): GpuArray;
325
+ /**
326
+ * Writes `values` into `target` at flat `indices`, in place. `op` `'set'` (one of several writes to an index wins),
327
+ * `'add'`, `'min'` or `'max'` (duplicates combine atomically, f32 included). Returns `target`.
328
+ */
329
+ scatter<T extends DType>(target: GpuArray<T>, indices: Operand, values: OperandLike, options?: {
330
+ readonly op?: 'set' | 'add' | 'min' | 'max';
331
+ }): GpuArray<T>;
332
+ /** How often each value occurs in a non-negative integer array (NumPy `bincount`), or the sum of `weights` per value. */
333
+ bincount(input: Operand, options: {
334
+ readonly weights?: Operand;
335
+ readonly length: number;
336
+ }): GpuArray;
337
+ /**
338
+ * Stream compaction without reading back: the elements whose mask is non-zero, packed at the front of `values`
339
+ * (capacity: the input size), and their `count` (u32, shape [1]) for an indirect dispatch or a later read.
340
+ */
341
+ compact(input: Operand, mask: Operand): {
342
+ readonly values: GpuArray;
343
+ readonly count: GpuArray<'u32'>;
344
+ };
345
+ /** The elements whose mask is non-zero, as an exactly sized array (reads the count back). */
346
+ filter(input: Operand, mask: Operand, options?: WaitOptions): Promise<GpuArray>;
347
+ /** Flat indices of the non-zero elements (u32), NumPy `flatnonzero`. Reads the count back. */
348
+ nonzero(input: Operand, options?: WaitOptions): Promise<GpuArray<'u32'>>;
349
+ /**
350
+ * Counts values in equal bins over `range` (default the data's own min and max, found on the GPU: nothing is read
351
+ * back), like NumPy's `histogram`: the last bin includes the maximum; values outside and NaN are not counted.
352
+ */
353
+ histogram(input: Operand, options?: HistogramOptions): Histogram;
354
+ /** Frees every array the context made, rejects pending reads, and destroys the device when the context opened it. */
355
+ dispose(): void;
356
+ /** Same as `dispose()`, for `using`. */
357
+ [Symbol.dispose](): void;
358
+ }
359
+ /**
360
+ * Opens a compute context. With `engine` (WebGPU backend) or `device` it shares that device; otherwise it opens a
361
+ * headless device of its own with the adapter's largest buffer and workgroup limits and, where available, the
362
+ * `shader-f16`, `timestamp-query` and `subgroups` features. Without WebGPU it falls back to the CPU (`backend`, default
363
+ * `'auto'`; check `gpu.backend`); with `backend: 'webgpu'` it rejects with a MargoError (`unsupported`) instead.
364
+ * @example
365
+ * using gpu = await createCompute();
366
+ * const sorted = await gpu.sort(gpu.array([3, 1, 2])).read(); // Float32Array [1, 2, 3]
367
+ */
368
+ export declare function createCompute(options?: CreateComputeOptions): Promise<ComputeContext>;