parakeet.js 0.0.2 → 0.0.3
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/.gitmodules +3 -0
- package/README.md +240 -239
- package/examples/hf-spaces-demo/README.md +6 -9
- package/examples/hf-spaces-demo/package.json +1 -1
- package/examples/hf-spaces-demo/src/App.js +307 -316
- package/examples/react-demo/package.json +19 -19
- package/examples/react-demo/src/App.jsx +324 -326
- package/examples/react-demo-dev/src/App.jsx +23 -24
- package/package.json +1 -1
- package/publish.ps1 +65 -0
- package/src/hub.js +235 -241
- package/src/parakeet.js +15 -8
- package/src/preprocessor.js +75 -68
- package/docs/parakeet-transformers-js/.gitattributes +0 -2
- package/docs/parakeet-transformers-js/.prettierignore +0 -8
- package/docs/parakeet-transformers-js/.prettierrc +0 -10
- package/docs/parakeet-transformers-js/.tmp_features.json +0 -1
- package/docs/parakeet-transformers-js/LICENSE +0 -202
- package/docs/parakeet-transformers-js/README.md +0 -448
- package/docs/parakeet-transformers-js/assets/nemo128.onnx +0 -0
- package/docs/parakeet-transformers-js/assets/nemo80.onnx +0 -0
- package/docs/parakeet-transformers-js/debug_test.js +0 -84
- package/docs/parakeet-transformers-js/dev/inspect_decoder.cjs +0 -9
- package/docs/parakeet-transformers-js/dev/inspect_joiner.cjs +0 -9
- package/docs/parakeet-transformers-js/dev/js_step_by_step.js +0 -249
- package/docs/parakeet-transformers-js/dev/parakeet_cli.js +0 -91
- package/docs/parakeet-transformers-js/jest.config.mjs +0 -194
- package/docs/parakeet-transformers-js/js_preprocessing.json +0 -225
- package/docs/parakeet-transformers-js/js_step_by_step.json +0 -837
- package/docs/parakeet-transformers-js/js_step_by_step_v2.json +0 -450
- package/docs/parakeet-transformers-js/js_step_by_step_v3.json +0 -450
- package/docs/parakeet-transformers-js/js_steps.json +0 -821
- package/docs/parakeet-transformers-js/package-lock.json +0 -12251
- package/docs/parakeet-transformers-js/package.json +0 -96
- package/docs/parakeet-transformers-js/src/audio_features.js +0 -178
- package/docs/parakeet-transformers-js/src/backends/onnx.js +0 -210
- package/docs/parakeet-transformers-js/src/base/feature_extraction_utils.js +0 -54
- package/docs/parakeet-transformers-js/src/base/image_processors_utils.js +0 -1105
- package/docs/parakeet-transformers-js/src/base/processing_utils.js +0 -173
- package/docs/parakeet-transformers-js/src/configs.js +0 -455
- package/docs/parakeet-transformers-js/src/env.js +0 -167
- package/docs/parakeet-transformers-js/src/generation/configuration_utils.js +0 -388
- package/docs/parakeet-transformers-js/src/generation/logits_process.js +0 -727
- package/docs/parakeet-transformers-js/src/generation/logits_sampler.js +0 -204
- package/docs/parakeet-transformers-js/src/generation/parameters.js +0 -35
- package/docs/parakeet-transformers-js/src/generation/stopping_criteria.js +0 -156
- package/docs/parakeet-transformers-js/src/generation/streamers.js +0 -225
- package/docs/parakeet-transformers-js/src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js +0 -85
- package/docs/parakeet-transformers-js/src/models/auto/feature_extraction_auto.js +0 -25
- package/docs/parakeet-transformers-js/src/models/auto/image_processing_auto.js +0 -29
- package/docs/parakeet-transformers-js/src/models/auto/processing_auto.js +0 -85
- package/docs/parakeet-transformers-js/src/models/beit/image_processing_beit.js +0 -5
- package/docs/parakeet-transformers-js/src/models/bit/image_processing_bit.js +0 -5
- package/docs/parakeet-transformers-js/src/models/chinese_clip/image_processing_chinese_clip.js +0 -5
- package/docs/parakeet-transformers-js/src/models/clap/feature_extraction_clap.js +0 -159
- package/docs/parakeet-transformers-js/src/models/clip/image_processing_clip.js +0 -6
- package/docs/parakeet-transformers-js/src/models/convnext/image_processing_convnext.js +0 -46
- package/docs/parakeet-transformers-js/src/models/dac/feature_extraction_dac.js +0 -3
- package/docs/parakeet-transformers-js/src/models/deit/image_processing_deit.js +0 -6
- package/docs/parakeet-transformers-js/src/models/detr/image_processing_detr.js +0 -52
- package/docs/parakeet-transformers-js/src/models/donut/image_processing_donut.js +0 -31
- package/docs/parakeet-transformers-js/src/models/dpt/image_processing_dpt.js +0 -6
- package/docs/parakeet-transformers-js/src/models/efficientnet/image_processing_efficientnet.js +0 -14
- package/docs/parakeet-transformers-js/src/models/encodec/feature_extraction_encodec.js +0 -32
- package/docs/parakeet-transformers-js/src/models/feature_extractors.js +0 -17
- package/docs/parakeet-transformers-js/src/models/florence2/processing_florence2.js +0 -131
- package/docs/parakeet-transformers-js/src/models/gemma3n/feature_extraction_gemma3n.js +0 -97
- package/docs/parakeet-transformers-js/src/models/gemma3n/processing_gemma3n.js +0 -74
- package/docs/parakeet-transformers-js/src/models/glpn/image_processing_glpn.js +0 -5
- package/docs/parakeet-transformers-js/src/models/grounding_dino/image_processing_grounding_dino.js +0 -29
- package/docs/parakeet-transformers-js/src/models/grounding_dino/processing_grounding_dino.js +0 -101
- package/docs/parakeet-transformers-js/src/models/idefics3/image_processing_idefics3.js +0 -232
- package/docs/parakeet-transformers-js/src/models/idefics3/processing_idefics3.js +0 -136
- package/docs/parakeet-transformers-js/src/models/image_processors.js +0 -40
- package/docs/parakeet-transformers-js/src/models/janus/image_processing_janus.js +0 -27
- package/docs/parakeet-transformers-js/src/models/janus/processing_janus.js +0 -123
- package/docs/parakeet-transformers-js/src/models/jina_clip/image_processing_jina_clip.js +0 -26
- package/docs/parakeet-transformers-js/src/models/jina_clip/processing_jina_clip.js +0 -24
- package/docs/parakeet-transformers-js/src/models/llava/processing_llava.js +0 -44
- package/docs/parakeet-transformers-js/src/models/llava_onevision/image_processing_llava_onevision.js +0 -5
- package/docs/parakeet-transformers-js/src/models/mask2former/image_processing_mask2former.js +0 -5
- package/docs/parakeet-transformers-js/src/models/maskformer/image_processing_maskformer.js +0 -18
- package/docs/parakeet-transformers-js/src/models/mgp_str/processing_mgp_str.js +0 -172
- package/docs/parakeet-transformers-js/src/models/mobilenet_v1/image_processing_mobilenet_v1.js +0 -7
- package/docs/parakeet-transformers-js/src/models/mobilenet_v2/image_processing_mobilenet_v2.js +0 -7
- package/docs/parakeet-transformers-js/src/models/mobilenet_v3/image_processing_mobilenet_v3.js +0 -7
- package/docs/parakeet-transformers-js/src/models/mobilenet_v4/image_processing_mobilenet_v4.js +0 -7
- package/docs/parakeet-transformers-js/src/models/mobilevit/image_processing_mobilevit.js +0 -6
- package/docs/parakeet-transformers-js/src/models/moonshine/feature_extraction_moonshine.js +0 -26
- package/docs/parakeet-transformers-js/src/models/moonshine/processing_moonshine.js +0 -20
- package/docs/parakeet-transformers-js/src/models/nougat/image_processing_nougat.js +0 -5
- package/docs/parakeet-transformers-js/src/models/owlv2/image_processing_owlv2.js +0 -5
- package/docs/parakeet-transformers-js/src/models/owlvit/image_processing_owlvit.js +0 -12
- package/docs/parakeet-transformers-js/src/models/owlvit/processing_owlvit.js +0 -7
- package/docs/parakeet-transformers-js/src/models/paligemma/processing_paligemma.js +0 -83
- package/docs/parakeet-transformers-js/src/models/parakeet/feature_extraction_parakeet.js +0 -3
- package/docs/parakeet-transformers-js/src/models/parakeet/modeling_parakeet.js +0 -3
- package/docs/parakeet-transformers-js/src/models/parakeet/processing_parakeet.js +0 -3
- package/docs/parakeet-transformers-js/src/models/parakeet/tokenization_parakeet.js +0 -3
- package/docs/parakeet-transformers-js/src/models/phi3_v/image_processing_phi3_v.js +0 -163
- package/docs/parakeet-transformers-js/src/models/phi3_v/processing_phi3_v.js +0 -53
- package/docs/parakeet-transformers-js/src/models/processors.js +0 -22
- package/docs/parakeet-transformers-js/src/models/pvt/image_processing_pvt.js +0 -5
- package/docs/parakeet-transformers-js/src/models/pyannote/feature_extraction_pyannote.js +0 -85
- package/docs/parakeet-transformers-js/src/models/pyannote/processing_pyannote.js +0 -24
- package/docs/parakeet-transformers-js/src/models/qwen2_vl/image_processing_qwen2_vl.js +0 -52
- package/docs/parakeet-transformers-js/src/models/qwen2_vl/processing_qwen2_vl.js +0 -53
- package/docs/parakeet-transformers-js/src/models/rt_detr/image_processing_rt_detr.js +0 -12
- package/docs/parakeet-transformers-js/src/models/sam/image_processing_sam.js +0 -242
- package/docs/parakeet-transformers-js/src/models/sam/processing_sam.js +0 -20
- package/docs/parakeet-transformers-js/src/models/sapiens/image_processing_sapiens.js +0 -13
- package/docs/parakeet-transformers-js/src/models/seamless_m4t/feature_extraction_seamless_m4t.js +0 -175
- package/docs/parakeet-transformers-js/src/models/segformer/image_processing_segformer.js +0 -13
- package/docs/parakeet-transformers-js/src/models/siglip/image_processing_siglip.js +0 -5
- package/docs/parakeet-transformers-js/src/models/smolvlm/image_processing_smolvlm.js +0 -2
- package/docs/parakeet-transformers-js/src/models/smolvlm/processing_smolvlm.js +0 -2
- package/docs/parakeet-transformers-js/src/models/snac/feature_extraction_snac.js +0 -3
- package/docs/parakeet-transformers-js/src/models/speecht5/feature_extraction_speecht5.js +0 -4
- package/docs/parakeet-transformers-js/src/models/speecht5/processing_speecht5.js +0 -17
- package/docs/parakeet-transformers-js/src/models/swin2sr/image_processing_swin2sr.js +0 -24
- package/docs/parakeet-transformers-js/src/models/ultravox/processing_ultravox.js +0 -54
- package/docs/parakeet-transformers-js/src/models/vit/image_processing_vit.js +0 -7
- package/docs/parakeet-transformers-js/src/models/vitmatte/image_processing_vitmatte.js +0 -50
- package/docs/parakeet-transformers-js/src/models/vitpose/image_processing_vitpose.js +0 -89
- package/docs/parakeet-transformers-js/src/models/wav2vec2/feature_extraction_wav2vec2.js +0 -44
- package/docs/parakeet-transformers-js/src/models/wav2vec2/processing_wav2vec2.js +0 -17
- package/docs/parakeet-transformers-js/src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js +0 -17
- package/docs/parakeet-transformers-js/src/models/wespeaker/feature_extraction_wespeaker.js +0 -95
- package/docs/parakeet-transformers-js/src/models/whisper/common_whisper.js +0 -157
- package/docs/parakeet-transformers-js/src/models/whisper/feature_extraction_whisper.js +0 -92
- package/docs/parakeet-transformers-js/src/models/whisper/generation_whisper.js +0 -89
- package/docs/parakeet-transformers-js/src/models/whisper/processing_whisper.js +0 -21
- package/docs/parakeet-transformers-js/src/models/yolos/image_processing_yolos.js +0 -12
- package/docs/parakeet-transformers-js/src/models.js +0 -8644
- package/docs/parakeet-transformers-js/src/ops/registry.js +0 -133
- package/docs/parakeet-transformers-js/src/ort_env.js +0 -8
- package/docs/parakeet-transformers-js/src/parakeet.js +0 -792
- package/docs/parakeet-transformers-js/src/pipelines.js +0 -3540
- package/docs/parakeet-transformers-js/src/processors.js +0 -16
- package/docs/parakeet-transformers-js/src/tokenizers.js +0 -4432
- package/docs/parakeet-transformers-js/src/transformers.js +0 -50
- package/docs/parakeet-transformers-js/src/utils/audio.js +0 -893
- package/docs/parakeet-transformers-js/src/utils/constants.js +0 -9
- package/docs/parakeet-transformers-js/src/utils/core.js +0 -259
- package/docs/parakeet-transformers-js/src/utils/data-structures.js +0 -574
- package/docs/parakeet-transformers-js/src/utils/devices.js +0 -22
- package/docs/parakeet-transformers-js/src/utils/dtypes.js +0 -63
- package/docs/parakeet-transformers-js/src/utils/generic.js +0 -35
- package/docs/parakeet-transformers-js/src/utils/hub.js +0 -780
- package/docs/parakeet-transformers-js/src/utils/image.js +0 -834
- package/docs/parakeet-transformers-js/src/utils/maths.js +0 -1061
- package/docs/parakeet-transformers-js/src/utils/tensor.js +0 -1539
- package/docs/parakeet-transformers-js/src/utils/video.js +0 -128
- package/docs/parakeet-transformers-js/test/decoder.test.js +0 -114
- package/docs/parakeet-transformers-js/test/encoder.test.js +0 -108
- package/docs/parakeet-transformers-js/test/preprocessor.test.js +0 -85
- package/docs/parakeet-transformers-js/test/tokenizer.test.js +0 -24
- package/docs/parakeet-transformers-js/test/transcribe.js +0 -89
- package/docs/parakeet-transformers-js/tsconfig.json +0 -21
- package/docs/parakeet-transformers-js/webpack.config.js +0 -223
|
@@ -1,1539 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @file Helper module for `Tensor` processing.
|
|
3
|
-
*
|
|
4
|
-
* These functions and classes are only used internally,
|
|
5
|
-
* meaning an end-user shouldn't need to access anything here.
|
|
6
|
-
*
|
|
7
|
-
* @module utils/tensor
|
|
8
|
-
*/
|
|
9
|
-
|
|
10
|
-
import {
|
|
11
|
-
interpolate_data,
|
|
12
|
-
max,
|
|
13
|
-
min,
|
|
14
|
-
permute_data
|
|
15
|
-
} from './maths.js';
|
|
16
|
-
|
|
17
|
-
import {
|
|
18
|
-
Tensor as ONNXTensor, isONNXTensor,
|
|
19
|
-
} from '../backends/onnx.js';
|
|
20
|
-
|
|
21
|
-
import { TensorOpRegistry } from '../ops/registry.js';
|
|
22
|
-
|
|
23
|
-
export const DataTypeMap = Object.freeze({
|
|
24
|
-
float32: Float32Array,
|
|
25
|
-
// @ts-ignore ts(2552) Limited availability of Float16Array across browsers:
|
|
26
|
-
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float16Array
|
|
27
|
-
float16: typeof Float16Array !== "undefined" ? Float16Array: Uint16Array,
|
|
28
|
-
float64: Float64Array,
|
|
29
|
-
string: Array, // string[]
|
|
30
|
-
int8: Int8Array,
|
|
31
|
-
uint8: Uint8Array,
|
|
32
|
-
int16: Int16Array,
|
|
33
|
-
uint16: Uint16Array,
|
|
34
|
-
int32: Int32Array,
|
|
35
|
-
uint32: Uint32Array,
|
|
36
|
-
int64: BigInt64Array,
|
|
37
|
-
uint64: BigUint64Array,
|
|
38
|
-
bool: Uint8Array,
|
|
39
|
-
uint4: Uint8Array,
|
|
40
|
-
int4: Int8Array,
|
|
41
|
-
});
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* @typedef {keyof typeof DataTypeMap} DataType
|
|
45
|
-
* @typedef {import('./maths.js').AnyTypedArray | any[]} DataArray
|
|
46
|
-
*/
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
export class Tensor {
|
|
50
|
-
/** @type {number[]} Dimensions of the tensor. */
|
|
51
|
-
get dims() {
|
|
52
|
-
// @ts-ignore
|
|
53
|
-
return this.ort_tensor.dims;
|
|
54
|
-
}
|
|
55
|
-
set dims(value) {
|
|
56
|
-
// FIXME: ONNXTensor declares dims as readonly so one needs to use the constructor() if dims change.
|
|
57
|
-
// @ts-ignore
|
|
58
|
-
this.ort_tensor.dims = value;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/** @type {DataType} Type of the tensor. */
|
|
62
|
-
get type() {
|
|
63
|
-
return this.ort_tensor.type;
|
|
64
|
-
};
|
|
65
|
-
|
|
66
|
-
/** @type {DataArray} The data stored in the tensor. */
|
|
67
|
-
get data() {
|
|
68
|
-
return this.ort_tensor.data;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/** @type {number} The number of elements in the tensor. */
|
|
72
|
-
get size() {
|
|
73
|
-
return this.ort_tensor.size;
|
|
74
|
-
};
|
|
75
|
-
|
|
76
|
-
/** @type {string} The location of the tensor data. */
|
|
77
|
-
get location() {
|
|
78
|
-
return this.ort_tensor.location;
|
|
79
|
-
};
|
|
80
|
-
|
|
81
|
-
ort_tensor;
|
|
82
|
-
|
|
83
|
-
/**
|
|
84
|
-
* Create a new Tensor or copy an existing Tensor.
|
|
85
|
-
* @param {[DataType, DataArray, number[]]|[ONNXTensor]} args
|
|
86
|
-
*/
|
|
87
|
-
constructor(...args) {
|
|
88
|
-
if (isONNXTensor(args[0])) {
|
|
89
|
-
this.ort_tensor = /** @type {ONNXTensor} */ (args[0]);
|
|
90
|
-
} else {
|
|
91
|
-
// Create new tensor
|
|
92
|
-
this.ort_tensor = new ONNXTensor(
|
|
93
|
-
/** @type {DataType} */(args[0]),
|
|
94
|
-
// @ts-expect-error ts(2769) Type 'number' is not assignable to type 'bigint'.
|
|
95
|
-
/** @type {Exclude<import('./maths.js').AnyTypedArray, Uint8ClampedArray>} */(args[1]),
|
|
96
|
-
args[2],
|
|
97
|
-
);
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
return new Proxy(this, {
|
|
101
|
-
get: (obj, key) => {
|
|
102
|
-
if (typeof key === 'string') {
|
|
103
|
-
let index = Number(key);
|
|
104
|
-
if (Number.isInteger(index)) {
|
|
105
|
-
// key is an integer (i.e., index)
|
|
106
|
-
return obj._getitem(index);
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
// @ts-ignore
|
|
110
|
-
return obj[key];
|
|
111
|
-
},
|
|
112
|
-
set: (obj, key, value) => {
|
|
113
|
-
// TODO allow setting of data
|
|
114
|
-
|
|
115
|
-
// @ts-ignore
|
|
116
|
-
return obj[key] = value;
|
|
117
|
-
}
|
|
118
|
-
});
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
dispose() {
|
|
122
|
-
this.ort_tensor.dispose();
|
|
123
|
-
// this.ort_tensor = undefined;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
/**
|
|
127
|
-
* Returns an iterator object for iterating over the tensor data in row-major order.
|
|
128
|
-
* If the tensor has more than one dimension, the iterator will yield subarrays.
|
|
129
|
-
* @returns {Iterator} An iterator object for iterating over the tensor data in row-major order.
|
|
130
|
-
*/
|
|
131
|
-
*[Symbol.iterator]() {
|
|
132
|
-
const [iterLength, ...iterDims] = this.dims;
|
|
133
|
-
|
|
134
|
-
if (iterDims.length > 0) {
|
|
135
|
-
const iterSize = iterDims.reduce((a, b) => a * b);
|
|
136
|
-
for (let i = 0; i < iterLength; ++i) {
|
|
137
|
-
yield this._subarray(i, iterSize, iterDims);
|
|
138
|
-
}
|
|
139
|
-
} else {
|
|
140
|
-
yield* this.data
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
/**
|
|
146
|
-
* Index into a Tensor object.
|
|
147
|
-
* @param {number} index The index to access.
|
|
148
|
-
* @returns {Tensor} The data at the specified index.
|
|
149
|
-
*/
|
|
150
|
-
_getitem(index) {
|
|
151
|
-
const [iterLength, ...iterDims] = this.dims;
|
|
152
|
-
|
|
153
|
-
index = safeIndex(index, iterLength);
|
|
154
|
-
|
|
155
|
-
if (iterDims.length > 0) {
|
|
156
|
-
const iterSize = iterDims.reduce((a, b) => a * b);
|
|
157
|
-
return this._subarray(index, iterSize, iterDims);
|
|
158
|
-
} else {
|
|
159
|
-
return new Tensor(this.type, [this.data[index]], iterDims);
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
/**
|
|
164
|
-
* @param {number|bigint} item The item to search for in the tensor
|
|
165
|
-
* @returns {number} The index of the first occurrence of item in the tensor data.
|
|
166
|
-
*/
|
|
167
|
-
indexOf(item) {
|
|
168
|
-
const this_data = this.data;
|
|
169
|
-
for (let index = 0; index < this_data.length; ++index) {
|
|
170
|
-
// Note: == instead of === so we can match Ints with BigInts
|
|
171
|
-
if (this_data[index] == item) {
|
|
172
|
-
return index;
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
return -1;
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
/**
|
|
179
|
-
* @param {number} index
|
|
180
|
-
* @param {number} iterSize
|
|
181
|
-
* @param {any} iterDims
|
|
182
|
-
* @returns {Tensor}
|
|
183
|
-
*/
|
|
184
|
-
_subarray(index, iterSize, iterDims) {
|
|
185
|
-
const o1 = index * iterSize;
|
|
186
|
-
const o2 = (index + 1) * iterSize;
|
|
187
|
-
|
|
188
|
-
// We use subarray if available (typed array), otherwise we use slice (normal array)
|
|
189
|
-
const data =
|
|
190
|
-
('subarray' in this.data)
|
|
191
|
-
? this.data.subarray(o1, o2)
|
|
192
|
-
: this.data.slice(o1, o2);
|
|
193
|
-
return new Tensor(this.type, data, iterDims);
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
/**
|
|
197
|
-
* Returns the value of this tensor as a standard JavaScript Number. This only works
|
|
198
|
-
* for tensors with one element. For other cases, see `Tensor.tolist()`.
|
|
199
|
-
* @returns {number|bigint} The value of this tensor as a standard JavaScript Number.
|
|
200
|
-
* @throws {Error} If the tensor has more than one element.
|
|
201
|
-
*/
|
|
202
|
-
item() {
|
|
203
|
-
const this_data = this.data;
|
|
204
|
-
if (this_data.length !== 1) {
|
|
205
|
-
throw new Error(`a Tensor with ${this_data.length} elements cannot be converted to Scalar`);
|
|
206
|
-
}
|
|
207
|
-
return this_data[0];
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
/**
|
|
211
|
-
* Convert tensor data to a n-dimensional JS list
|
|
212
|
-
* @returns {Array}
|
|
213
|
-
*/
|
|
214
|
-
tolist() {
|
|
215
|
-
return reshape(this.data, this.dims)
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
/**
|
|
219
|
-
* Return a new Tensor with the sigmoid function applied to each element.
|
|
220
|
-
* @returns {Tensor} The tensor with the sigmoid function applied.
|
|
221
|
-
*/
|
|
222
|
-
sigmoid() {
|
|
223
|
-
return this.clone().sigmoid_();
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
/**
|
|
227
|
-
* Applies the sigmoid function to the tensor in place.
|
|
228
|
-
* @returns {Tensor} Returns `this`.
|
|
229
|
-
*/
|
|
230
|
-
sigmoid_() {
|
|
231
|
-
const this_data = this.data;
|
|
232
|
-
for (let i = 0; i < this_data.length; ++i) {
|
|
233
|
-
this_data[i] = 1 / (1 + Math.exp(-this_data[i]));
|
|
234
|
-
}
|
|
235
|
-
return this;
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
/**
|
|
239
|
-
* Return a new Tensor with a callback function applied to each element.
|
|
240
|
-
* @param {Function} callback - The function to apply to each element. It should take three arguments:
|
|
241
|
-
* the current element, its index, and the tensor's data array.
|
|
242
|
-
* @returns {Tensor} A new Tensor with the callback function applied to each element.
|
|
243
|
-
*/
|
|
244
|
-
map(callback) {
|
|
245
|
-
return this.clone().map_(callback);
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
/**
|
|
249
|
-
* Apply a callback function to each element of the tensor in place.
|
|
250
|
-
* @param {Function} callback - The function to apply to each element. It should take three arguments:
|
|
251
|
-
* the current element, its index, and the tensor's data array.
|
|
252
|
-
* @returns {Tensor} Returns `this`.
|
|
253
|
-
*/
|
|
254
|
-
map_(callback) {
|
|
255
|
-
const this_data = this.data;
|
|
256
|
-
for (let i = 0; i < this_data.length; ++i) {
|
|
257
|
-
this_data[i] = callback(this_data[i], i, this_data);
|
|
258
|
-
}
|
|
259
|
-
return this;
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
/**
|
|
263
|
-
* Return a new Tensor with every element multiplied by a constant.
|
|
264
|
-
* @param {number} val The value to multiply by.
|
|
265
|
-
* @returns {Tensor} The new tensor.
|
|
266
|
-
*/
|
|
267
|
-
mul(val) {
|
|
268
|
-
return this.clone().mul_(val);
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
/**
|
|
272
|
-
* Multiply the tensor by a constant in place.
|
|
273
|
-
* @param {number} val The value to multiply by.
|
|
274
|
-
* @returns {Tensor} Returns `this`.
|
|
275
|
-
*/
|
|
276
|
-
mul_(val) {
|
|
277
|
-
const this_data = this.data;
|
|
278
|
-
for (let i = 0; i < this_data.length; ++i) {
|
|
279
|
-
this_data[i] *= val;
|
|
280
|
-
}
|
|
281
|
-
return this;
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
/**
|
|
285
|
-
* Return a new Tensor with every element divided by a constant.
|
|
286
|
-
* @param {number} val The value to divide by.
|
|
287
|
-
* @returns {Tensor} The new tensor.
|
|
288
|
-
*/
|
|
289
|
-
div(val) {
|
|
290
|
-
return this.clone().div_(val);
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
/**
|
|
294
|
-
* Divide the tensor by a constant in place.
|
|
295
|
-
* @param {number} val The value to divide by.
|
|
296
|
-
* @returns {Tensor} Returns `this`.
|
|
297
|
-
*/
|
|
298
|
-
div_(val) {
|
|
299
|
-
const this_data = this.data;
|
|
300
|
-
for (let i = 0; i < this_data.length; ++i) {
|
|
301
|
-
this_data[i] /= val;
|
|
302
|
-
}
|
|
303
|
-
return this;
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
/**
|
|
307
|
-
* Return a new Tensor with every element added by a constant.
|
|
308
|
-
* @param {number} val The value to add by.
|
|
309
|
-
* @returns {Tensor} The new tensor.
|
|
310
|
-
*/
|
|
311
|
-
add(val) {
|
|
312
|
-
return this.clone().add_(val);
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
/**
|
|
316
|
-
* Add the tensor by a constant in place.
|
|
317
|
-
* @param {number} val The value to add by.
|
|
318
|
-
* @returns {Tensor} Returns `this`.
|
|
319
|
-
*/
|
|
320
|
-
add_(val) {
|
|
321
|
-
const this_data = this.data;
|
|
322
|
-
for (let i = 0; i < this_data.length; ++i) {
|
|
323
|
-
this_data[i] += val;
|
|
324
|
-
}
|
|
325
|
-
return this;
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
/**
|
|
329
|
-
* Return a new Tensor with every element subtracted by a constant.
|
|
330
|
-
* @param {number} val The value to subtract by.
|
|
331
|
-
* @returns {Tensor} The new tensor.
|
|
332
|
-
*/
|
|
333
|
-
sub(val) {
|
|
334
|
-
return this.clone().sub_(val);
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
/**
|
|
338
|
-
* Subtract the tensor by a constant in place.
|
|
339
|
-
* @param {number} val The value to subtract by.
|
|
340
|
-
* @returns {Tensor} Returns `this`.
|
|
341
|
-
*/
|
|
342
|
-
sub_(val) {
|
|
343
|
-
const this_data = this.data;
|
|
344
|
-
for (let i = 0; i < this_data.length; ++i) {
|
|
345
|
-
this_data[i] -= val;
|
|
346
|
-
}
|
|
347
|
-
return this;
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
/**
|
|
351
|
-
* Creates a deep copy of the current Tensor.
|
|
352
|
-
* @returns {Tensor} A new Tensor with the same type, data, and dimensions as the original.
|
|
353
|
-
*/
|
|
354
|
-
clone() {
|
|
355
|
-
return new Tensor(this.type, this.data.slice(), this.dims.slice());
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
/**
|
|
359
|
-
* Performs a slice operation on the Tensor along specified dimensions.
|
|
360
|
-
*
|
|
361
|
-
* Consider a Tensor that has a dimension of [4, 7]:
|
|
362
|
-
* ```
|
|
363
|
-
* [ 1, 2, 3, 4, 5, 6, 7]
|
|
364
|
-
* [ 8, 9, 10, 11, 12, 13, 14]
|
|
365
|
-
* [15, 16, 17, 18, 19, 20, 21]
|
|
366
|
-
* [22, 23, 24, 25, 26, 27, 28]
|
|
367
|
-
* ```
|
|
368
|
-
* We can slice against the two dims of row and column, for instance in this
|
|
369
|
-
* case we can start at the second element, and return to the second last,
|
|
370
|
-
* like this:
|
|
371
|
-
* ```
|
|
372
|
-
* tensor.slice([1, -1], [1, -1]);
|
|
373
|
-
* ```
|
|
374
|
-
* which would return:
|
|
375
|
-
* ```
|
|
376
|
-
* [ 9, 10, 11, 12, 13 ]
|
|
377
|
-
* [ 16, 17, 18, 19, 20 ]
|
|
378
|
-
* ```
|
|
379
|
-
*
|
|
380
|
-
* @param {...(number|number[]|null)} slices The slice specifications for each dimension.
|
|
381
|
-
* - If a number is given, then a single element is selected.
|
|
382
|
-
* - If an array of two numbers is given, then a range of elements [start, end (exclusive)] is selected.
|
|
383
|
-
* - If null is given, then the entire dimension is selected.
|
|
384
|
-
* @returns {Tensor} A new Tensor containing the selected elements.
|
|
385
|
-
* @throws {Error} If the slice input is invalid.
|
|
386
|
-
*/
|
|
387
|
-
slice(...slices) {
|
|
388
|
-
// This allows for slicing with ranges and numbers
|
|
389
|
-
const newTensorDims = [];
|
|
390
|
-
const newOffsets = [];
|
|
391
|
-
|
|
392
|
-
// slices is an array of numbers or arrays of numbers
|
|
393
|
-
// e.g., slices = [0, [1, 3], null, [0, 3]]
|
|
394
|
-
for (let sliceIndex = 0; sliceIndex < this.dims.length; ++sliceIndex) {
|
|
395
|
-
let slice = slices[sliceIndex];
|
|
396
|
-
|
|
397
|
-
if (slice === null || slice === undefined) {
|
|
398
|
-
// null or undefined means take the whole dimension
|
|
399
|
-
newOffsets.push([0, this.dims[sliceIndex]]);
|
|
400
|
-
newTensorDims.push(this.dims[sliceIndex]);
|
|
401
|
-
|
|
402
|
-
} else if (typeof slice === 'number') {
|
|
403
|
-
slice = safeIndex(slice, this.dims[sliceIndex], sliceIndex);
|
|
404
|
-
|
|
405
|
-
// A number means take a single element
|
|
406
|
-
newOffsets.push([slice, slice + 1]);
|
|
407
|
-
|
|
408
|
-
} else if (Array.isArray(slice) && slice.length === 2) {
|
|
409
|
-
// An array of length 2 means take a range of elements
|
|
410
|
-
let [start, end] = slice;
|
|
411
|
-
start = start === null
|
|
412
|
-
? 0
|
|
413
|
-
: safeIndex(start, this.dims[sliceIndex], sliceIndex, false);
|
|
414
|
-
end = end === null
|
|
415
|
-
? this.dims[sliceIndex]
|
|
416
|
-
: safeIndex(end, this.dims[sliceIndex], sliceIndex, false);
|
|
417
|
-
|
|
418
|
-
if (start > end) {
|
|
419
|
-
throw new Error(`Invalid slice: ${slice}`);
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
const offsets = [
|
|
423
|
-
Math.max(start, 0),
|
|
424
|
-
Math.min(end, this.dims[sliceIndex])
|
|
425
|
-
];
|
|
426
|
-
|
|
427
|
-
newOffsets.push(offsets);
|
|
428
|
-
newTensorDims.push(offsets[1] - offsets[0]);
|
|
429
|
-
|
|
430
|
-
} else {
|
|
431
|
-
throw new Error(`Invalid slice: ${slice}`);
|
|
432
|
-
}
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
const newDims = newOffsets.map(([start, end]) => end - start);
|
|
436
|
-
const newBufferSize = newDims.reduce((a, b) => a * b);
|
|
437
|
-
|
|
438
|
-
const this_data = this.data;
|
|
439
|
-
// Allocate memory
|
|
440
|
-
// @ts-ignore
|
|
441
|
-
const data = new this_data.constructor(newBufferSize);
|
|
442
|
-
|
|
443
|
-
// Precompute strides
|
|
444
|
-
const stride = this.stride();
|
|
445
|
-
|
|
446
|
-
for (let i = 0; i < newBufferSize; ++i) {
|
|
447
|
-
let originalIndex = 0;
|
|
448
|
-
for (let j = newDims.length - 1, num = i; j >= 0; --j) {
|
|
449
|
-
const size = newDims[j];
|
|
450
|
-
originalIndex += ((num % size) + newOffsets[j][0]) * stride[j];
|
|
451
|
-
num = Math.floor(num / size);
|
|
452
|
-
}
|
|
453
|
-
data[i] = this_data[originalIndex];
|
|
454
|
-
}
|
|
455
|
-
return new Tensor(this.type, data, newTensorDims);
|
|
456
|
-
}
|
|
457
|
-
|
|
458
|
-
/**
|
|
459
|
-
* Return a permuted version of this Tensor, according to the provided dimensions.
|
|
460
|
-
* @param {...number} dims Dimensions to permute.
|
|
461
|
-
* @returns {Tensor} The permuted tensor.
|
|
462
|
-
*/
|
|
463
|
-
permute(...dims) {
|
|
464
|
-
return permute(this, dims);
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
// TODO: implement transpose. For now (backwards compatibility), it's just an alias for permute()
|
|
468
|
-
transpose(...dims) {
|
|
469
|
-
return this.permute(...dims);
|
|
470
|
-
}
|
|
471
|
-
|
|
472
|
-
/**
|
|
473
|
-
* Returns the sum of each row of the input tensor in the given dimension dim.
|
|
474
|
-
*
|
|
475
|
-
* @param {number} [dim=null] The dimension or dimensions to reduce. If `null`, all dimensions are reduced.
|
|
476
|
-
* @param {boolean} keepdim Whether the output tensor has `dim` retained or not.
|
|
477
|
-
* @returns The summed tensor
|
|
478
|
-
*/
|
|
479
|
-
sum(dim = null, keepdim = false) {
|
|
480
|
-
return this.norm(1, dim, keepdim);
|
|
481
|
-
}
|
|
482
|
-
|
|
483
|
-
/**
|
|
484
|
-
* Returns the matrix norm or vector norm of a given tensor.
|
|
485
|
-
* @param {number|string} [p='fro'] The order of norm
|
|
486
|
-
* @param {number} [dim=null] Specifies which dimension of the tensor to calculate the norm across.
|
|
487
|
-
* If dim is None, the norm will be calculated across all dimensions of input.
|
|
488
|
-
* @param {boolean} [keepdim=false] Whether the output tensors have dim retained or not.
|
|
489
|
-
* @returns {Tensor} The norm of the tensor.
|
|
490
|
-
*/
|
|
491
|
-
norm(p = 'fro', dim = null, keepdim = false) {
|
|
492
|
-
if (p === 'fro') {
|
|
493
|
-
// NOTE: Since we only support integer dims, Frobenius norm produces the same result as p=2.
|
|
494
|
-
p = 2;
|
|
495
|
-
} else if (typeof p === 'string') {
|
|
496
|
-
throw Error(`Unsupported norm: ${p}`);
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
const this_data = this.data;
|
|
500
|
-
const fn = (a, b) => a + (b ** p);
|
|
501
|
-
|
|
502
|
-
if (dim === null) {
|
|
503
|
-
// @ts-ignore
|
|
504
|
-
const val = this_data.reduce(fn, 0) ** (1 / p);
|
|
505
|
-
return new Tensor(this.type, [val], []);
|
|
506
|
-
}
|
|
507
|
-
|
|
508
|
-
const [type, result, resultDims] = reduce_helper(fn, this, dim, keepdim);
|
|
509
|
-
|
|
510
|
-
if (p !== 1) {
|
|
511
|
-
for (let i = 0; i < result.length; ++i) {
|
|
512
|
-
result[i] = result[i] ** (1 / p);
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
|
-
return new Tensor(type, result, resultDims);
|
|
516
|
-
}
|
|
517
|
-
|
|
518
|
-
/**
|
|
519
|
-
* Performs `L_p` normalization of inputs over specified dimension. Operates in place.
|
|
520
|
-
* @param {number} [p=2] The exponent value in the norm formulation
|
|
521
|
-
* @param {number} [dim=1] The dimension to reduce
|
|
522
|
-
* @returns {Tensor} `this` for operation chaining.
|
|
523
|
-
*/
|
|
524
|
-
normalize_(p = 2.0, dim = 1) {
|
|
525
|
-
dim = safeIndex(dim, this.dims.length);
|
|
526
|
-
|
|
527
|
-
const norm = this.norm(p, dim, true);
|
|
528
|
-
|
|
529
|
-
const this_data = this.data;
|
|
530
|
-
const norm_data = norm.data;
|
|
531
|
-
for (let i = 0; i < this_data.length; ++i) {
|
|
532
|
-
|
|
533
|
-
// Calculate the index in the resulting array
|
|
534
|
-
let resultIndex = 0;
|
|
535
|
-
|
|
536
|
-
for (let j = this.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {
|
|
537
|
-
const size = this.dims[j];
|
|
538
|
-
if (j !== dim) {
|
|
539
|
-
const index = num % size;
|
|
540
|
-
resultIndex += index * resultMultiplier;
|
|
541
|
-
resultMultiplier *= this.dims[j];
|
|
542
|
-
}
|
|
543
|
-
num = Math.floor(num / size);
|
|
544
|
-
}
|
|
545
|
-
|
|
546
|
-
// Divide by normalized value
|
|
547
|
-
this_data[i] /= norm_data[resultIndex];
|
|
548
|
-
}
|
|
549
|
-
|
|
550
|
-
return this;
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
/**
|
|
554
|
-
* Performs `L_p` normalization of inputs over specified dimension.
|
|
555
|
-
* @param {number} [p=2] The exponent value in the norm formulation
|
|
556
|
-
* @param {number} [dim=1] The dimension to reduce
|
|
557
|
-
* @returns {Tensor} The normalized tensor.
|
|
558
|
-
*/
|
|
559
|
-
normalize(p = 2.0, dim = 1) {
|
|
560
|
-
return this.clone().normalize_(p, dim);
|
|
561
|
-
}
|
|
562
|
-
|
|
563
|
-
/**
|
|
564
|
-
* Compute and return the stride of this tensor.
|
|
565
|
-
* Stride is the jump necessary to go from one element to the next one in the specified dimension dim.
|
|
566
|
-
* @returns {number[]} The stride of this tensor.
|
|
567
|
-
*/
|
|
568
|
-
stride() {
|
|
569
|
-
return dimsToStride(this.dims);
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
/**
|
|
573
|
-
* Returns a tensor with all specified dimensions of input of size 1 removed.
|
|
574
|
-
*
|
|
575
|
-
* NOTE: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other.
|
|
576
|
-
* If you would like a copy, use `tensor.clone()` before squeezing.
|
|
577
|
-
*
|
|
578
|
-
* @param {number|number[]} [dim=null] If given, the input will be squeezed only in the specified dimensions.
|
|
579
|
-
* @returns {Tensor} The squeezed tensor
|
|
580
|
-
*/
|
|
581
|
-
squeeze(dim = null) {
|
|
582
|
-
return new Tensor(
|
|
583
|
-
this.type,
|
|
584
|
-
this.data,
|
|
585
|
-
calc_squeeze_dims(this.dims, dim)
|
|
586
|
-
)
|
|
587
|
-
}
|
|
588
|
-
|
|
589
|
-
/**
|
|
590
|
-
* In-place version of @see {@link Tensor.squeeze}
|
|
591
|
-
*/
|
|
592
|
-
squeeze_(dim = null) {
|
|
593
|
-
this.dims = calc_squeeze_dims(this.dims, dim);
|
|
594
|
-
return this;
|
|
595
|
-
}
|
|
596
|
-
|
|
597
|
-
/**
|
|
598
|
-
* Returns a new tensor with a dimension of size one inserted at the specified position.
|
|
599
|
-
*
|
|
600
|
-
* NOTE: The returned tensor shares the same underlying data with this tensor.
|
|
601
|
-
*
|
|
602
|
-
* @param {number} dim The index at which to insert the singleton dimension
|
|
603
|
-
* @returns {Tensor} The unsqueezed tensor
|
|
604
|
-
*/
|
|
605
|
-
unsqueeze(dim = null) {
|
|
606
|
-
return new Tensor(
|
|
607
|
-
this.type,
|
|
608
|
-
this.data,
|
|
609
|
-
calc_unsqueeze_dims(this.dims, dim)
|
|
610
|
-
);
|
|
611
|
-
}
|
|
612
|
-
|
|
613
|
-
/**
|
|
614
|
-
* In-place version of @see {@link Tensor.unsqueeze}
|
|
615
|
-
*/
|
|
616
|
-
unsqueeze_(dim = null) {
|
|
617
|
-
this.dims = calc_unsqueeze_dims(this.dims, dim);
|
|
618
|
-
return this;
|
|
619
|
-
}
|
|
620
|
-
|
|
621
|
-
/**
|
|
622
|
-
* In-place version of @see {@link Tensor.flatten}
|
|
623
|
-
*/
|
|
624
|
-
flatten_(start_dim = 0, end_dim = -1) {
|
|
625
|
-
// TODO validate inputs
|
|
626
|
-
end_dim = (end_dim + this.dims.length) % this.dims.length;
|
|
627
|
-
|
|
628
|
-
let dimsToKeepBefore = this.dims.slice(0, start_dim);
|
|
629
|
-
let dimsToFlatten = this.dims.slice(start_dim, end_dim + 1);
|
|
630
|
-
let dimsToKeepAfter = this.dims.slice(end_dim + 1);
|
|
631
|
-
|
|
632
|
-
this.dims = [...dimsToKeepBefore, dimsToFlatten.reduce((a, b) => a * b, 1), ...dimsToKeepAfter]
|
|
633
|
-
return this;
|
|
634
|
-
}
|
|
635
|
-
|
|
636
|
-
/**
|
|
637
|
-
* Flattens input by reshaping it into a one-dimensional tensor.
|
|
638
|
-
* If `start_dim` or `end_dim` are passed, only dimensions starting with `start_dim`
|
|
639
|
-
* and ending with `end_dim` are flattened. The order of elements in input is unchanged.
|
|
640
|
-
* @param {number} start_dim the first dim to flatten
|
|
641
|
-
* @param {number} end_dim the last dim to flatten
|
|
642
|
-
* @returns {Tensor} The flattened tensor.
|
|
643
|
-
*/
|
|
644
|
-
flatten(start_dim = 0, end_dim = -1) {
|
|
645
|
-
return this.clone().flatten_(start_dim, end_dim);
|
|
646
|
-
}
|
|
647
|
-
|
|
648
|
-
/**
|
|
649
|
-
* Returns a new tensor with the same data as the `self` tensor but of a different `shape`.
|
|
650
|
-
* @param {...number} dims the desired size
|
|
651
|
-
* @returns {Tensor} The tensor with the same data but different shape
|
|
652
|
-
*/
|
|
653
|
-
view(...dims) {
|
|
654
|
-
// TODO: validate dims
|
|
655
|
-
let inferredIndex = -1;
|
|
656
|
-
for (let i = 0; i < dims.length; ++i) {
|
|
657
|
-
if (dims[i] === -1) {
|
|
658
|
-
if (inferredIndex !== -1) {
|
|
659
|
-
throw new Error("Only one dimension can be inferred");
|
|
660
|
-
}
|
|
661
|
-
inferredIndex = i;
|
|
662
|
-
}
|
|
663
|
-
}
|
|
664
|
-
|
|
665
|
-
const this_data = this.data;
|
|
666
|
-
if (inferredIndex !== -1) {
|
|
667
|
-
// Some dimension must be inferred
|
|
668
|
-
const productOther = dims.reduce((product, curr, index) => {
|
|
669
|
-
return index !== inferredIndex ? product * curr : product
|
|
670
|
-
}, 1);
|
|
671
|
-
|
|
672
|
-
dims[inferredIndex] = this_data.length / productOther;
|
|
673
|
-
}
|
|
674
|
-
return new Tensor(this.type, this_data, dims); // NOTE: uses same underlying storage
|
|
675
|
-
}
|
|
676
|
-
|
|
677
|
-
neg_() {
|
|
678
|
-
const this_data = this.data;
|
|
679
|
-
for (let i = 0; i < this_data.length; ++i) {
|
|
680
|
-
this_data[i] = -this_data[i];
|
|
681
|
-
}
|
|
682
|
-
return this;
|
|
683
|
-
}
|
|
684
|
-
neg() {
|
|
685
|
-
return this.clone().neg_();
|
|
686
|
-
}
|
|
687
|
-
|
|
688
|
-
/**
|
|
689
|
-
* Computes input > val element-wise.
|
|
690
|
-
* @param {number} val The value to compare with.
|
|
691
|
-
* @returns {Tensor} A boolean tensor that is `true` where input is greater than other and `false` elsewhere.
|
|
692
|
-
*/
|
|
693
|
-
gt(val) {
|
|
694
|
-
const mask = new Uint8Array(this.data.length);
|
|
695
|
-
const this_data = this.data;
|
|
696
|
-
for (let i = 0; i < this_data.length; ++i) {
|
|
697
|
-
mask[i] = this_data[i] > val ? 1 : 0;
|
|
698
|
-
}
|
|
699
|
-
return new Tensor('bool', mask, this.dims);
|
|
700
|
-
}
|
|
701
|
-
|
|
702
|
-
/**
|
|
703
|
-
* Computes input < val element-wise.
|
|
704
|
-
* @param {number} val The value to compare with.
|
|
705
|
-
* @returns {Tensor} A boolean tensor that is `true` where input is less than other and `false` elsewhere.
|
|
706
|
-
*/
|
|
707
|
-
lt(val) {
|
|
708
|
-
const mask = new Uint8Array(this.data.length);
|
|
709
|
-
const this_data = this.data;
|
|
710
|
-
for (let i = 0; i < this_data.length; ++i) {
|
|
711
|
-
mask[i] = this_data[i] < val ? 1 : 0;
|
|
712
|
-
}
|
|
713
|
-
return new Tensor('bool', mask, this.dims);
|
|
714
|
-
}
|
|
715
|
-
|
|
716
|
-
/**
|
|
717
|
-
* In-place version of @see {@link Tensor.clamp}
|
|
718
|
-
*/
|
|
719
|
-
clamp_(min, max) {
|
|
720
|
-
const this_data = this.data;
|
|
721
|
-
for (let i = 0; i < this_data.length; ++i) {
|
|
722
|
-
this_data[i] = Math.min(Math.max(this_data[i], min), max);
|
|
723
|
-
}
|
|
724
|
-
return this;
|
|
725
|
-
}
|
|
726
|
-
|
|
727
|
-
/**
|
|
728
|
-
* Clamps all elements in input into the range [ min, max ]
|
|
729
|
-
* @param {number} min lower-bound of the range to be clamped to
|
|
730
|
-
* @param {number} max upper-bound of the range to be clamped to
|
|
731
|
-
* @returns {Tensor} the output tensor.
|
|
732
|
-
*/
|
|
733
|
-
clamp(min, max) {
|
|
734
|
-
return this.clone().clamp_(min, max);
|
|
735
|
-
}
|
|
736
|
-
|
|
737
|
-
/**
|
|
738
|
-
* In-place version of @see {@link Tensor.round}
|
|
739
|
-
*/
|
|
740
|
-
round_() {
|
|
741
|
-
const this_data = this.data;
|
|
742
|
-
for (let i = 0; i < this_data.length; ++i) {
|
|
743
|
-
this_data[i] = Math.round(this_data[i]);
|
|
744
|
-
}
|
|
745
|
-
return this;
|
|
746
|
-
}
|
|
747
|
-
|
|
748
|
-
/**
|
|
749
|
-
* Rounds elements of input to the nearest integer.
|
|
750
|
-
* @returns {Tensor} the output tensor.
|
|
751
|
-
*/
|
|
752
|
-
round() {
|
|
753
|
-
return this.clone().round_();
|
|
754
|
-
}
|
|
755
|
-
|
|
756
|
-
mean(dim = null, keepdim = false) {
|
|
757
|
-
return mean(this, dim, keepdim);
|
|
758
|
-
}
|
|
759
|
-
|
|
760
|
-
min(dim = null, keepdim = false) {
|
|
761
|
-
if (dim === null) {
|
|
762
|
-
// None to reduce over all dimensions.
|
|
763
|
-
const val = min(this.data)[0];
|
|
764
|
-
return new Tensor(this.type, [val], [/* scalar */]);
|
|
765
|
-
}
|
|
766
|
-
const [type, result, resultDims] = reduce_helper((a, b) => Math.min(a, b), this, dim, keepdim, Infinity);
|
|
767
|
-
return new Tensor(type, result, resultDims);
|
|
768
|
-
}
|
|
769
|
-
|
|
770
|
-
max(dim = null, keepdim = false) {
|
|
771
|
-
if (dim === null) {
|
|
772
|
-
// None to reduce over all dimensions.
|
|
773
|
-
const val = max(this.data)[0];
|
|
774
|
-
return new Tensor(this.type, [val], [/* scalar */]);
|
|
775
|
-
}
|
|
776
|
-
const [type, result, resultDims] = reduce_helper((a, b) => Math.max(a, b), this, dim, keepdim, -Infinity);
|
|
777
|
-
return new Tensor(type, result, resultDims);
|
|
778
|
-
}
|
|
779
|
-
|
|
780
|
-
argmin(dim = null, keepdim = false) {
|
|
781
|
-
if (dim !== null) {
|
|
782
|
-
throw new Error("`dim !== null` not yet implemented.");
|
|
783
|
-
}
|
|
784
|
-
const index = min(this.data)[1];
|
|
785
|
-
return new Tensor('int64', [BigInt(index)], []);
|
|
786
|
-
}
|
|
787
|
-
argmax(dim = null, keepdim = false) {
|
|
788
|
-
if (dim !== null) {
|
|
789
|
-
throw new Error("`dim !== null` not yet implemented.");
|
|
790
|
-
}
|
|
791
|
-
const index = max(this.data)[1];
|
|
792
|
-
return new Tensor('int64', [BigInt(index)], []);
|
|
793
|
-
}
|
|
794
|
-
|
|
795
|
-
/**
|
|
796
|
-
* Performs Tensor dtype conversion.
|
|
797
|
-
* @param {DataType} type The desired data type.
|
|
798
|
-
* @returns {Tensor} The converted tensor.
|
|
799
|
-
*/
|
|
800
|
-
to(type) {
|
|
801
|
-
// If the self Tensor already has the correct dtype, then self is returned.
|
|
802
|
-
if (this.type === type) return this;
|
|
803
|
-
|
|
804
|
-
// Otherwise, the returned tensor is a copy of self with the desired dtype.
|
|
805
|
-
if (!DataTypeMap.hasOwnProperty(type)) {
|
|
806
|
-
throw new Error(`Unsupported type: ${type}`);
|
|
807
|
-
}
|
|
808
|
-
|
|
809
|
-
// Handle special cases where a mapping function is needed (e.g., where one type is a bigint and the other is a number)
|
|
810
|
-
let map_fn;
|
|
811
|
-
const is_source_bigint = ['int64', 'uint64'].includes(this.type);
|
|
812
|
-
const is_dest_bigint = ['int64', 'uint64'].includes(type);
|
|
813
|
-
if (is_source_bigint && !is_dest_bigint) {
|
|
814
|
-
// TypeError: Cannot convert a BigInt value to a number
|
|
815
|
-
map_fn = Number;
|
|
816
|
-
} else if (!is_source_bigint && is_dest_bigint) {
|
|
817
|
-
// TypeError: Cannot convert [x] to a BigInt
|
|
818
|
-
map_fn = BigInt;
|
|
819
|
-
}
|
|
820
|
-
|
|
821
|
-
// @ts-ignore
|
|
822
|
-
return new Tensor(type, DataTypeMap[type].from(this.data, map_fn), this.dims);
|
|
823
|
-
}
|
|
824
|
-
}
|
|
825
|
-
|
|
826
|
-
/**
|
|
827
|
-
* This creates a nested array of a given type and depth (see examples).
|
|
828
|
-
*
|
|
829
|
-
* @example
|
|
830
|
-
* NestArray<string, 1>; // string[]
|
|
831
|
-
* @example
|
|
832
|
-
* NestArray<number, 2>; // number[][]
|
|
833
|
-
* @example
|
|
834
|
-
* NestArray<string, 3>; // string[][][] etc.
|
|
835
|
-
* @template T
|
|
836
|
-
* @template {number} Depth
|
|
837
|
-
* @template {never[]} [Acc=[]]
|
|
838
|
-
* @typedef {Acc['length'] extends Depth ? T : NestArray<T[], Depth, [...Acc, never]>} NestArray
|
|
839
|
-
*/
|
|
840
|
-
|
|
841
|
-
/**
|
|
842
|
-
* Reshapes a 1-dimensional array into an n-dimensional array, according to the provided dimensions.
|
|
843
|
-
*
|
|
844
|
-
* @example
|
|
845
|
-
* reshape([10 ], [1 ]); // Type: number[] Value: [10]
|
|
846
|
-
* reshape([1, 2, 3, 4 ], [2, 2 ]); // Type: number[][] Value: [[1, 2], [3, 4]]
|
|
847
|
-
* reshape([1, 2, 3, 4, 5, 6, 7, 8], [2, 2, 2]); // Type: number[][][] Value: [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
|
|
848
|
-
* reshape([1, 2, 3, 4, 5, 6, 7, 8], [4, 2 ]); // Type: number[][] Value: [[1, 2], [3, 4], [5, 6], [7, 8]]
|
|
849
|
-
* @param {T[]|DataArray} data The input array to reshape.
|
|
850
|
-
* @param {DIM} dimensions The target shape/dimensions.
|
|
851
|
-
* @template T
|
|
852
|
-
* @template {[number]|number[]} DIM
|
|
853
|
-
* @returns {NestArray<T, DIM["length"]>} The reshaped array.
|
|
854
|
-
*/
|
|
855
|
-
function reshape(data, dimensions) {
|
|
856
|
-
|
|
857
|
-
const totalElements = data.length;
|
|
858
|
-
const dimensionSize = dimensions.reduce((a, b) => a * b);
|
|
859
|
-
|
|
860
|
-
if (totalElements !== dimensionSize) {
|
|
861
|
-
throw Error(`cannot reshape array of size ${totalElements} into shape (${dimensions})`);
|
|
862
|
-
}
|
|
863
|
-
|
|
864
|
-
/** @type {any} */
|
|
865
|
-
let reshapedArray = data;
|
|
866
|
-
|
|
867
|
-
for (let i = dimensions.length - 1; i >= 0; i--) {
|
|
868
|
-
reshapedArray = reshapedArray.reduce((acc, val) => {
|
|
869
|
-
let lastArray = acc[acc.length - 1];
|
|
870
|
-
|
|
871
|
-
if (lastArray.length < dimensions[i]) {
|
|
872
|
-
lastArray.push(val);
|
|
873
|
-
} else {
|
|
874
|
-
acc.push([val]);
|
|
875
|
-
}
|
|
876
|
-
|
|
877
|
-
return acc;
|
|
878
|
-
}, [[]]);
|
|
879
|
-
}
|
|
880
|
-
|
|
881
|
-
return reshapedArray[0];
|
|
882
|
-
}
|
|
883
|
-
|
|
884
|
-
/**
|
|
885
|
-
* Permutes a tensor according to the provided axes.
|
|
886
|
-
* @param {any} tensor The input tensor to permute.
|
|
887
|
-
* @param {Array} axes The axes to permute the tensor along.
|
|
888
|
-
* @returns {Tensor} The permuted tensor.
|
|
889
|
-
*/
|
|
890
|
-
export function permute(tensor, axes) {
|
|
891
|
-
const [permutedData, shape] = permute_data(tensor.data, tensor.dims, axes);
|
|
892
|
-
return new Tensor(tensor.type, permutedData, shape);
|
|
893
|
-
}
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
/**
|
|
897
|
-
* Interpolates an Tensor to the given size.
|
|
898
|
-
* @param {Tensor} input The input tensor to interpolate. Data must be channel-first (i.e., [c, h, w])
|
|
899
|
-
* @param {number[]} size The output size of the image
|
|
900
|
-
* @param {string} mode The interpolation mode
|
|
901
|
-
* @param {boolean} align_corners Whether to align corners.
|
|
902
|
-
* @returns {Tensor} The interpolated tensor.
|
|
903
|
-
*/
|
|
904
|
-
export function interpolate(input, [out_height, out_width], mode = 'bilinear', align_corners = false) {
|
|
905
|
-
|
|
906
|
-
// Input image dimensions
|
|
907
|
-
const in_channels = input.dims.at(-3) ?? 1;
|
|
908
|
-
const in_height = input.dims.at(-2);
|
|
909
|
-
const in_width = input.dims.at(-1);
|
|
910
|
-
|
|
911
|
-
let output = interpolate_data(
|
|
912
|
-
/** @type {import('./maths.js').TypedArray}*/(input.data),
|
|
913
|
-
[in_channels, in_height, in_width],
|
|
914
|
-
[out_height, out_width],
|
|
915
|
-
mode,
|
|
916
|
-
align_corners
|
|
917
|
-
);
|
|
918
|
-
return new Tensor(input.type, output, [in_channels, out_height, out_width]);
|
|
919
|
-
}
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
/**
|
|
923
|
-
* Down/up samples the input.
|
|
924
|
-
* Inspired by https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html.
|
|
925
|
-
* @param {Tensor} input the input tensor
|
|
926
|
-
* @param {Object} options the options for the interpolation
|
|
927
|
-
* @param {[number, number]|[number, number, number]|[number, number, number, number]} [options.size=null] output spatial size.
|
|
928
|
-
* @param {"nearest"|"bilinear"|"bicubic"} [options.mode='bilinear'] algorithm used for upsampling
|
|
929
|
-
* @returns {Promise<Tensor>} The interpolated tensor.
|
|
930
|
-
*/
|
|
931
|
-
export async function interpolate_4d(input, {
|
|
932
|
-
size = null,
|
|
933
|
-
mode = 'bilinear',
|
|
934
|
-
} = {}) {
|
|
935
|
-
|
|
936
|
-
// Error checking
|
|
937
|
-
if (input.dims.length !== 4) {
|
|
938
|
-
throw new Error('`interpolate_4d` currently only supports 4D input.');
|
|
939
|
-
}
|
|
940
|
-
if (!size) {
|
|
941
|
-
// TODO: support scale_factor
|
|
942
|
-
throw new Error('`interpolate_4d` requires a `size` argument.');
|
|
943
|
-
}
|
|
944
|
-
|
|
945
|
-
// Fill in missing dimensions
|
|
946
|
-
let targetDims;
|
|
947
|
-
if (size.length === 2) {
|
|
948
|
-
targetDims = [...input.dims.slice(0, 2), ...size];
|
|
949
|
-
} else if (size.length === 3) {
|
|
950
|
-
targetDims = [input.dims[0], ...size];
|
|
951
|
-
} else if (size.length === 4) {
|
|
952
|
-
targetDims = size;
|
|
953
|
-
} else {
|
|
954
|
-
throw new Error('`size` must be of length 2, 3, or 4.');
|
|
955
|
-
}
|
|
956
|
-
|
|
957
|
-
let op;
|
|
958
|
-
if (mode === 'nearest') {
|
|
959
|
-
op = await TensorOpRegistry.nearest_interpolate_4d;
|
|
960
|
-
} else if (mode === 'bilinear') {
|
|
961
|
-
op = await TensorOpRegistry.bilinear_interpolate_4d;
|
|
962
|
-
} else if (mode === 'bicubic') {
|
|
963
|
-
op = await TensorOpRegistry.bicubic_interpolate_4d;
|
|
964
|
-
} else {
|
|
965
|
-
throw new Error(`Unsupported mode: ${mode}`);
|
|
966
|
-
}
|
|
967
|
-
|
|
968
|
-
const sizeTensor = new Tensor('int64', new BigInt64Array(targetDims.map(BigInt)), [targetDims.length]);
|
|
969
|
-
return await op({ x: input, s: sizeTensor });
|
|
970
|
-
}
|
|
971
|
-
|
|
972
|
-
/**
|
|
973
|
-
* Matrix product of two tensors.
|
|
974
|
-
* Inspired by https://pytorch.org/docs/stable/generated/torch.matmul.html
|
|
975
|
-
* @param {Tensor} a the first tensor to be multiplied
|
|
976
|
-
* @param {Tensor} b the second tensor to be multiplied
|
|
977
|
-
* @returns {Promise<Tensor>} The matrix product of the two tensors.
|
|
978
|
-
*/
|
|
979
|
-
export async function matmul(a, b) {
|
|
980
|
-
const op = await TensorOpRegistry.matmul;
|
|
981
|
-
return await op({ a, b });
|
|
982
|
-
}
|
|
983
|
-
|
|
984
|
-
/**
|
|
985
|
-
* Computes the one dimensional Fourier transform of real-valued input.
|
|
986
|
-
* Inspired by https://pytorch.org/docs/stable/generated/torch.fft.rfft.html
|
|
987
|
-
* @param {Tensor} x the real input tensor
|
|
988
|
-
* @param {Tensor} a The dimension along which to take the one dimensional real FFT.
|
|
989
|
-
* @returns {Promise<Tensor>} the output tensor.
|
|
990
|
-
*/
|
|
991
|
-
export async function rfft(x, a) {
|
|
992
|
-
const op = await TensorOpRegistry.rfft;
|
|
993
|
-
return await op({ x, a });
|
|
994
|
-
}
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
/**
|
|
998
|
-
* Returns the k largest elements of the given input tensor.
|
|
999
|
-
* Inspired by https://pytorch.org/docs/stable/generated/torch.topk.html
|
|
1000
|
-
* @param {Tensor} x the input tensor
|
|
1001
|
-
* @param {number} [k] the k in "top-k"
|
|
1002
|
-
* @returns {Promise<[Tensor, Tensor]>} the output tuple of (Tensor, LongTensor) of top-k elements and their indices.
|
|
1003
|
-
*/
|
|
1004
|
-
export async function topk(x, k) {
|
|
1005
|
-
const op = await TensorOpRegistry.top_k;
|
|
1006
|
-
|
|
1007
|
-
if (k == null) {
|
|
1008
|
-
k = x.dims.at(-1);
|
|
1009
|
-
} else {
|
|
1010
|
-
k = Math.min(k, x.dims.at(-1));
|
|
1011
|
-
}
|
|
1012
|
-
return await op({
|
|
1013
|
-
x,
|
|
1014
|
-
k: new Tensor(
|
|
1015
|
-
'int64',
|
|
1016
|
-
[BigInt(k)],
|
|
1017
|
-
[1]
|
|
1018
|
-
)
|
|
1019
|
-
});
|
|
1020
|
-
}
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
const arrayToIndexTensor = (array) => new Tensor('int64', array, [array.length]);
|
|
1024
|
-
/**
|
|
1025
|
-
* Slice a multidimensional float32 tensor.
|
|
1026
|
-
* @param {Tensor} data: Tensor of data to extract slices from
|
|
1027
|
-
* @param {number[]} starts: 1-D array of starting indices of corresponding axis in axes
|
|
1028
|
-
* @param {number[]} ends: 1-D array of ending indices (exclusive) of corresponding axis in axes
|
|
1029
|
-
* @param {number[]} axes: 1-D array of axes that starts and ends apply to
|
|
1030
|
-
* @param {number[]} [steps]: 1-D array of slice step of corresponding axis in axes.
|
|
1031
|
-
* @returns {Promise<Tensor>} Sliced data tensor.
|
|
1032
|
-
*/
|
|
1033
|
-
export async function slice(data, starts, ends, axes, steps) {
|
|
1034
|
-
const op = await TensorOpRegistry.slice;
|
|
1035
|
-
return await op({
|
|
1036
|
-
x: data,
|
|
1037
|
-
s: arrayToIndexTensor(starts),
|
|
1038
|
-
e: arrayToIndexTensor(ends),
|
|
1039
|
-
a: arrayToIndexTensor(axes),
|
|
1040
|
-
t: arrayToIndexTensor(steps ?? new Array(axes.length).fill(1)),
|
|
1041
|
-
});
|
|
1042
|
-
}
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
/**
|
|
1046
|
-
* Perform mean pooling of the last hidden state followed by a normalization step.
|
|
1047
|
-
* @param {Tensor} last_hidden_state Tensor of shape [batchSize, seqLength, embedDim]
|
|
1048
|
-
* @param {Tensor} attention_mask Tensor of shape [batchSize, seqLength]
|
|
1049
|
-
* @returns {Tensor} Returns a new Tensor of shape [batchSize, embedDim].
|
|
1050
|
-
*/
|
|
1051
|
-
export function mean_pooling(last_hidden_state, attention_mask) {
|
|
1052
|
-
// last_hidden_state: [batchSize, seqLength, embedDim]
|
|
1053
|
-
// attention_mask: [batchSize, seqLength]
|
|
1054
|
-
const lastHiddenStateData = last_hidden_state.data;
|
|
1055
|
-
const attentionMaskData = attention_mask.data;
|
|
1056
|
-
|
|
1057
|
-
const shape = [last_hidden_state.dims[0], last_hidden_state.dims[2]];
|
|
1058
|
-
|
|
1059
|
-
// @ts-ignore
|
|
1060
|
-
const returnedData = new lastHiddenStateData.constructor(shape[0] * shape[1]);
|
|
1061
|
-
const [batchSize, seqLength, embedDim] = last_hidden_state.dims;
|
|
1062
|
-
|
|
1063
|
-
let outIndex = 0;
|
|
1064
|
-
for (let i = 0; i < batchSize; ++i) {
|
|
1065
|
-
const offset = i * embedDim * seqLength;
|
|
1066
|
-
|
|
1067
|
-
for (let k = 0; k < embedDim; ++k) {
|
|
1068
|
-
let sum = 0;
|
|
1069
|
-
let count = 0;
|
|
1070
|
-
|
|
1071
|
-
const attnMaskOffset = i * seqLength;
|
|
1072
|
-
const offset2 = offset + k;
|
|
1073
|
-
// Pool over all words in sequence
|
|
1074
|
-
for (let j = 0; j < seqLength; ++j) {
|
|
1075
|
-
// index into attention mask
|
|
1076
|
-
const attn = Number(attentionMaskData[attnMaskOffset + j]);
|
|
1077
|
-
|
|
1078
|
-
count += attn;
|
|
1079
|
-
sum += lastHiddenStateData[offset2 + j * embedDim] * attn;
|
|
1080
|
-
}
|
|
1081
|
-
|
|
1082
|
-
const avg = sum / count;
|
|
1083
|
-
returnedData[outIndex++] = avg;
|
|
1084
|
-
}
|
|
1085
|
-
}
|
|
1086
|
-
|
|
1087
|
-
return new Tensor(
|
|
1088
|
-
last_hidden_state.type,
|
|
1089
|
-
returnedData,
|
|
1090
|
-
shape
|
|
1091
|
-
)
|
|
1092
|
-
}
|
|
1093
|
-
|
|
1094
|
-
/**
|
|
1095
|
-
* Apply Layer Normalization for last certain number of dimensions.
|
|
1096
|
-
* @param {Tensor} input The input tensor
|
|
1097
|
-
* @param {number[]} normalized_shape input shape from an expected input of size
|
|
1098
|
-
* @param {Object} options The options for the layer normalization
|
|
1099
|
-
* @param {number} [options.eps=1e-5] A value added to the denominator for numerical stability.
|
|
1100
|
-
* @returns {Tensor} The normalized tensor.
|
|
1101
|
-
*/
|
|
1102
|
-
export function layer_norm(input, normalized_shape, {
|
|
1103
|
-
eps = 1e-5,
|
|
1104
|
-
} = {}) {
|
|
1105
|
-
if (input.dims.length !== 2) {
|
|
1106
|
-
throw new Error('`layer_norm` currently only supports 2D input.');
|
|
1107
|
-
}
|
|
1108
|
-
|
|
1109
|
-
const [batchSize, featureDim] = input.dims;
|
|
1110
|
-
|
|
1111
|
-
if (normalized_shape.length !== 1 && normalized_shape[0] !== featureDim) {
|
|
1112
|
-
throw new Error('`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.');
|
|
1113
|
-
}
|
|
1114
|
-
|
|
1115
|
-
const [std, mean] = std_mean(input, 1, 0, true);
|
|
1116
|
-
const stdData = /** @type {Float32Array} */(std.data);
|
|
1117
|
-
const meanData = /** @type {Float32Array} */(mean.data);
|
|
1118
|
-
|
|
1119
|
-
const inputData = /** @type {Float32Array} */(input.data);
|
|
1120
|
-
|
|
1121
|
-
// @ts-ignore
|
|
1122
|
-
const returnedData = new inputData.constructor(inputData.length);
|
|
1123
|
-
|
|
1124
|
-
for (let i = 0; i < batchSize; ++i) {
|
|
1125
|
-
const offset = i * featureDim;
|
|
1126
|
-
for (let j = 0; j < featureDim; ++j) {
|
|
1127
|
-
const offset2 = offset + j;
|
|
1128
|
-
returnedData[offset2] = (inputData[offset2] - meanData[i]) / (stdData[i] + eps);
|
|
1129
|
-
}
|
|
1130
|
-
}
|
|
1131
|
-
return new Tensor(input.type, returnedData, input.dims);
|
|
1132
|
-
}
|
|
1133
|
-
|
|
1134
|
-
/**
|
|
1135
|
-
* Helper function to calculate new dimensions when performing a squeeze operation.
|
|
1136
|
-
* @param {number[]} dims The dimensions of the tensor.
|
|
1137
|
-
* @param {number|number[]|null} dim The dimension(s) to squeeze.
|
|
1138
|
-
* @returns {number[]} The new dimensions.
|
|
1139
|
-
* @private
|
|
1140
|
-
*/
|
|
1141
|
-
function calc_squeeze_dims(dims, dim) {
|
|
1142
|
-
dims = dims.slice();
|
|
1143
|
-
if (dim === null) {
|
|
1144
|
-
dims = dims.filter((d) => d !== 1);
|
|
1145
|
-
} else if (typeof dim === 'number') {
|
|
1146
|
-
if (dims[dim] === 1) {
|
|
1147
|
-
dims.splice(dim, 1);
|
|
1148
|
-
}
|
|
1149
|
-
} else if (Array.isArray(dim)) {
|
|
1150
|
-
dims = dims.filter((x, i) => {
|
|
1151
|
-
return x !== 1 || !dim.includes(i);
|
|
1152
|
-
});
|
|
1153
|
-
}
|
|
1154
|
-
return dims;
|
|
1155
|
-
}
|
|
1156
|
-
|
|
1157
|
-
/**
|
|
1158
|
-
* Helper function to calculate new dimensions when performing an unsqueeze operation.
|
|
1159
|
-
* @param {number[]} dims The dimensions of the tensor.
|
|
1160
|
-
* @param {number} dim The dimension to unsqueeze.
|
|
1161
|
-
* @returns {number[]} The new dimensions.
|
|
1162
|
-
* @private
|
|
1163
|
-
*/
|
|
1164
|
-
function calc_unsqueeze_dims(dims, dim) {
|
|
1165
|
-
// Dimension out of range (e.g., "expected to be in range of [-4, 3], but got 4")
|
|
1166
|
-
// + 1 since we allow inserting at the end (i.e. dim = -1)
|
|
1167
|
-
dim = safeIndex(dim, dims.length + 1);
|
|
1168
|
-
dims = dims.slice();
|
|
1169
|
-
// Insert 1 into specified dimension
|
|
1170
|
-
dims.splice(dim, 0, 1);
|
|
1171
|
-
return dims;
|
|
1172
|
-
}
|
|
1173
|
-
|
|
1174
|
-
/**
|
|
1175
|
-
* Safely calculate the index for an array of a given size, allowing negative indexing.
|
|
1176
|
-
* @param {number} index The index that will be used.
|
|
1177
|
-
* @param {number} size The size of the array.
|
|
1178
|
-
* @param {number} [dimension=null] The dimension that the index is for (optional).
|
|
1179
|
-
* @returns {number} The index, guaranteed to be non-negative and less than `arrayLength`.
|
|
1180
|
-
*
|
|
1181
|
-
* @throws {Error} If the index is out of range.
|
|
1182
|
-
* @private
|
|
1183
|
-
*/
|
|
1184
|
-
function safeIndex(index, size, dimension = null, boundsCheck = true) {
|
|
1185
|
-
if (index < -size || index >= size) {
|
|
1186
|
-
if (boundsCheck) {
|
|
1187
|
-
throw new Error(`IndexError: index ${index} is out of bounds for dimension${dimension === null ? '' : ' ' + dimension} with size ${size}`);
|
|
1188
|
-
} else {
|
|
1189
|
-
return index < -size ? 0 : size;
|
|
1190
|
-
}
|
|
1191
|
-
}
|
|
1192
|
-
|
|
1193
|
-
if (index < 0) {
|
|
1194
|
-
// Negative indexing, ensuring positive index
|
|
1195
|
-
index = ((index % size) + size) % size;
|
|
1196
|
-
}
|
|
1197
|
-
return index;
|
|
1198
|
-
}
|
|
1199
|
-
|
|
1200
|
-
/**
|
|
1201
|
-
* Concatenates an array of tensors along a specified dimension.
|
|
1202
|
-
* @param {Tensor[]} tensors The array of tensors to concatenate.
|
|
1203
|
-
* @param {number} dim The dimension to concatenate along.
|
|
1204
|
-
* @returns {Tensor} The concatenated tensor.
|
|
1205
|
-
*/
|
|
1206
|
-
export function cat(tensors, dim = 0) {
|
|
1207
|
-
dim = safeIndex(dim, tensors[0].dims.length);
|
|
1208
|
-
|
|
1209
|
-
// TODO do validation of shapes
|
|
1210
|
-
|
|
1211
|
-
const resultDims = tensors[0].dims.slice();
|
|
1212
|
-
resultDims[dim] = tensors.reduce((a, b) => a + b.dims[dim], 0);
|
|
1213
|
-
|
|
1214
|
-
// Create a new array to store the accumulated values
|
|
1215
|
-
const resultSize = resultDims.reduce((a, b) => a * b, 1);
|
|
1216
|
-
// @ts-ignore
|
|
1217
|
-
const result = new tensors[0].data.constructor(resultSize);
|
|
1218
|
-
|
|
1219
|
-
// Create output tensor of same type as first
|
|
1220
|
-
const resultType = tensors[0].type;
|
|
1221
|
-
|
|
1222
|
-
if (dim === 0) {
|
|
1223
|
-
// Handle special case for performance reasons
|
|
1224
|
-
|
|
1225
|
-
let offset = 0;
|
|
1226
|
-
for (const tensor of tensors) {
|
|
1227
|
-
const tensorData = tensor.data;
|
|
1228
|
-
result.set(tensorData, offset);
|
|
1229
|
-
offset += tensorData.length;
|
|
1230
|
-
}
|
|
1231
|
-
|
|
1232
|
-
} else {
|
|
1233
|
-
|
|
1234
|
-
let currentDim = 0;
|
|
1235
|
-
|
|
1236
|
-
for (let t = 0; t < tensors.length; ++t) {
|
|
1237
|
-
const { data, dims } = tensors[t];
|
|
1238
|
-
|
|
1239
|
-
// Iterate over the data array
|
|
1240
|
-
for (let i = 0; i < data.length; ++i) {
|
|
1241
|
-
// Calculate the index in the resulting array
|
|
1242
|
-
let resultIndex = 0;
|
|
1243
|
-
|
|
1244
|
-
for (let j = dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {
|
|
1245
|
-
const size = dims[j];
|
|
1246
|
-
let index = num % size;
|
|
1247
|
-
if (j === dim) {
|
|
1248
|
-
index += currentDim;
|
|
1249
|
-
}
|
|
1250
|
-
resultIndex += index * resultMultiplier;
|
|
1251
|
-
resultMultiplier *= resultDims[j];
|
|
1252
|
-
num = Math.floor(num / size);
|
|
1253
|
-
}
|
|
1254
|
-
// Accumulate the value at the current index
|
|
1255
|
-
result[resultIndex] = data[i];
|
|
1256
|
-
}
|
|
1257
|
-
|
|
1258
|
-
currentDim += dims[dim];
|
|
1259
|
-
}
|
|
1260
|
-
}
|
|
1261
|
-
return new Tensor(resultType, result, resultDims);
|
|
1262
|
-
}
|
|
1263
|
-
|
|
1264
|
-
/**
|
|
1265
|
-
* Stack an array of tensors along a specified dimension.
|
|
1266
|
-
* @param {Tensor[]} tensors The array of tensors to stack.
|
|
1267
|
-
* @param {number} dim The dimension to stack along.
|
|
1268
|
-
* @returns {Tensor} The stacked tensor.
|
|
1269
|
-
*/
|
|
1270
|
-
export function stack(tensors, dim = 0) {
|
|
1271
|
-
// TODO do validation of shapes
|
|
1272
|
-
// NOTE: stack expects each tensor to be equal size
|
|
1273
|
-
return cat(tensors.map(t => t.unsqueeze(dim)), dim);
|
|
1274
|
-
}
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
/**
|
|
1278
|
-
* @param {(previousValue: any, currentValue: any, currentIndex?: number, resultIndex?: number) => any} callbackfn
|
|
1279
|
-
* @param {Tensor} input the input tensor.
|
|
1280
|
-
* @param {number|null} dim the dimension to reduce.
|
|
1281
|
-
* @param {boolean} keepdim whether the output tensor has dim retained or not.
|
|
1282
|
-
* @returns {[DataType, any, number[]]} The reduced tensor data.
|
|
1283
|
-
*/
|
|
1284
|
-
function reduce_helper(callbackfn, input, dim = null, keepdim = false, initialValue = null) {
|
|
1285
|
-
const inputData = input.data;
|
|
1286
|
-
const inputDims = input.dims;
|
|
1287
|
-
|
|
1288
|
-
// Negative indexing
|
|
1289
|
-
dim = safeIndex(dim, inputDims.length);
|
|
1290
|
-
|
|
1291
|
-
// Calculate the shape of the resulting array after summation
|
|
1292
|
-
const resultDims = inputDims.slice(); // Copy the original dimensions
|
|
1293
|
-
resultDims[dim] = 1; // Remove the specified axis
|
|
1294
|
-
|
|
1295
|
-
// Create a new array to store the accumulated values
|
|
1296
|
-
// @ts-ignore
|
|
1297
|
-
const result = new inputData.constructor(inputData.length / inputDims[dim]);
|
|
1298
|
-
if (initialValue !== null) {
|
|
1299
|
-
result.fill(initialValue);
|
|
1300
|
-
}
|
|
1301
|
-
|
|
1302
|
-
// Iterate over the data array
|
|
1303
|
-
for (let i = 0; i < inputData.length; ++i) {
|
|
1304
|
-
|
|
1305
|
-
// Calculate the index in the resulting array
|
|
1306
|
-
let resultIndex = 0;
|
|
1307
|
-
|
|
1308
|
-
for (let j = inputDims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {
|
|
1309
|
-
const size = inputDims[j];
|
|
1310
|
-
if (j !== dim) {
|
|
1311
|
-
const index = num % size;
|
|
1312
|
-
resultIndex += index * resultMultiplier;
|
|
1313
|
-
resultMultiplier *= resultDims[j];
|
|
1314
|
-
}
|
|
1315
|
-
num = Math.floor(num / size);
|
|
1316
|
-
}
|
|
1317
|
-
|
|
1318
|
-
// Accumulate the value at the current index
|
|
1319
|
-
result[resultIndex] = callbackfn(result[resultIndex], inputData[i], i, resultIndex);
|
|
1320
|
-
}
|
|
1321
|
-
|
|
1322
|
-
if (!keepdim) resultDims.splice(dim, 1);
|
|
1323
|
-
|
|
1324
|
-
return [input.type, result, resultDims];
|
|
1325
|
-
}
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
/**
|
|
1329
|
-
* Calculates the standard deviation and mean over the dimensions specified by dim. dim can be a single dimension or `null` to reduce over all dimensions.
|
|
1330
|
-
* @param {Tensor} input the input tenso
|
|
1331
|
-
* @param {number|null} dim the dimension to reduce. If None, all dimensions are reduced.
|
|
1332
|
-
* @param {number} correction difference between the sample size and sample degrees of freedom. Defaults to Bessel's correction, correction=1.
|
|
1333
|
-
* @param {boolean} keepdim whether the output tensor has dim retained or not.
|
|
1334
|
-
* @returns {Tensor[]} A tuple of (std, mean) tensors.
|
|
1335
|
-
*/
|
|
1336
|
-
export function std_mean(input, dim = null, correction = 1, keepdim = false) {
|
|
1337
|
-
const inputData = /** @type {Float32Array} */(input.data);
|
|
1338
|
-
const inputDims = input.dims;
|
|
1339
|
-
|
|
1340
|
-
if (dim === null) {
|
|
1341
|
-
// None to reduce over all dimensions.
|
|
1342
|
-
const sum = inputData.reduce((a, b) => a + b, 0);
|
|
1343
|
-
const mean = sum / inputData.length;
|
|
1344
|
-
const std = Math.sqrt(inputData.reduce((a, b) => a + (b - mean) ** 2, 0) / (inputData.length - correction));
|
|
1345
|
-
|
|
1346
|
-
const meanTensor = new Tensor(input.type, [mean], [/* scalar */]);
|
|
1347
|
-
const stdTensor = new Tensor(input.type, [std], [/* scalar */]);
|
|
1348
|
-
|
|
1349
|
-
return [stdTensor, meanTensor];
|
|
1350
|
-
}
|
|
1351
|
-
dim = safeIndex(dim, inputDims.length);
|
|
1352
|
-
const meanTensor = mean(input, dim, keepdim);
|
|
1353
|
-
const meanTensorData = meanTensor.data;
|
|
1354
|
-
|
|
1355
|
-
// Compute squared sum
|
|
1356
|
-
const [type, result, resultDims] = reduce_helper((a, b, i, j) => a + (b - meanTensorData[j]) ** 2, input, dim, keepdim);
|
|
1357
|
-
|
|
1358
|
-
// Square root of the squared sum
|
|
1359
|
-
for (let i = 0; i < result.length; ++i) {
|
|
1360
|
-
result[i] = Math.sqrt(result[i] / (inputDims[dim] - correction));
|
|
1361
|
-
}
|
|
1362
|
-
|
|
1363
|
-
const stdTensor = new Tensor(type, result, resultDims);
|
|
1364
|
-
|
|
1365
|
-
return [stdTensor, meanTensor];
|
|
1366
|
-
}
|
|
1367
|
-
|
|
1368
|
-
/**
|
|
1369
|
-
* Returns the mean value of each row of the input tensor in the given dimension dim.
|
|
1370
|
-
* @param {Tensor} input the input tensor.
|
|
1371
|
-
* @param {number|null} dim the dimension to reduce.
|
|
1372
|
-
* @param {boolean} keepdim whether the output tensor has dim retained or not.
|
|
1373
|
-
* @returns {Tensor} A new tensor with means taken along the specified dimension.
|
|
1374
|
-
*/
|
|
1375
|
-
export function mean(input, dim = null, keepdim = false) {
|
|
1376
|
-
const inputDims = input.dims;
|
|
1377
|
-
const inputData = /** @type {Float32Array} */(input.data);
|
|
1378
|
-
|
|
1379
|
-
if (dim === null) {
|
|
1380
|
-
// None to reduce over all dimensions.
|
|
1381
|
-
const val = inputData.reduce((a, b) => a + b, 0);
|
|
1382
|
-
return new Tensor(input.type, [val / inputData.length], [/* scalar */]);
|
|
1383
|
-
}
|
|
1384
|
-
dim = safeIndex(dim, inputDims.length);
|
|
1385
|
-
|
|
1386
|
-
// Compute sum
|
|
1387
|
-
const [type, result, resultDims] = reduce_helper((a, b) => a + b, input, dim, keepdim);
|
|
1388
|
-
|
|
1389
|
-
// Divide by number of elements in the dimension
|
|
1390
|
-
if (inputDims[dim] !== 1) {
|
|
1391
|
-
for (let i = 0; i < result.length; ++i) {
|
|
1392
|
-
result[i] /= inputDims[dim];
|
|
1393
|
-
}
|
|
1394
|
-
}
|
|
1395
|
-
|
|
1396
|
-
return new Tensor(type, result, resultDims);
|
|
1397
|
-
}
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
function dimsToStride(dims) {
|
|
1401
|
-
const stride = new Array(dims.length);
|
|
1402
|
-
for (let i = dims.length - 1, s2 = 1; i >= 0; --i) {
|
|
1403
|
-
stride[i] = s2;
|
|
1404
|
-
s2 *= dims[i];
|
|
1405
|
-
}
|
|
1406
|
-
return stride;
|
|
1407
|
-
}
|
|
1408
|
-
|
|
1409
|
-
function fullHelper(size, fill_value, dtype, cls) {
|
|
1410
|
-
const numElements = size.reduce((a, b) => a * b, 1);
|
|
1411
|
-
return new Tensor(
|
|
1412
|
-
dtype,
|
|
1413
|
-
new cls(numElements).fill(fill_value),
|
|
1414
|
-
size
|
|
1415
|
-
)
|
|
1416
|
-
}
|
|
1417
|
-
|
|
1418
|
-
/**
|
|
1419
|
-
* Creates a tensor of size size filled with fill_value. The tensor's dtype is inferred from fill_value.
|
|
1420
|
-
* @param {number[]} size A sequence of integers defining the shape of the output tensor.
|
|
1421
|
-
* @param {number|bigint|boolean} fill_value The value to fill the output tensor with.
|
|
1422
|
-
* @returns {Tensor} The filled tensor.
|
|
1423
|
-
*/
|
|
1424
|
-
export function full(size, fill_value) {
|
|
1425
|
-
let dtype;
|
|
1426
|
-
let typedArrayCls;
|
|
1427
|
-
if (typeof fill_value === 'number') {
|
|
1428
|
-
dtype = 'float32';
|
|
1429
|
-
typedArrayCls = Float32Array;
|
|
1430
|
-
} else if (typeof fill_value === 'bigint') {
|
|
1431
|
-
dtype = 'int64';
|
|
1432
|
-
typedArrayCls = BigInt64Array;
|
|
1433
|
-
} else if (typeof fill_value === 'boolean') {
|
|
1434
|
-
dtype = 'bool';
|
|
1435
|
-
typedArrayCls = Uint8Array;
|
|
1436
|
-
} else {
|
|
1437
|
-
// TODO: support other dtypes
|
|
1438
|
-
throw new Error(`Unsupported data type: ${typeof fill_value}`);
|
|
1439
|
-
}
|
|
1440
|
-
return fullHelper(size, fill_value, dtype, typedArrayCls);
|
|
1441
|
-
}
|
|
1442
|
-
|
|
1443
|
-
export function full_like(tensor, fill_value) {
|
|
1444
|
-
return full(tensor.dims, fill_value);
|
|
1445
|
-
}
|
|
1446
|
-
|
|
1447
|
-
/**
|
|
1448
|
-
* Returns a tensor filled with the scalar value 1, with the shape defined by the variable argument size.
|
|
1449
|
-
* @param {number[]} size A sequence of integers defining the shape of the output tensor.
|
|
1450
|
-
* @returns {Tensor} The ones tensor.
|
|
1451
|
-
*/
|
|
1452
|
-
export function ones(size) {
|
|
1453
|
-
return fullHelper(size, 1n, 'int64', BigInt64Array);
|
|
1454
|
-
}
|
|
1455
|
-
|
|
1456
|
-
/**
|
|
1457
|
-
* Returns a tensor filled with the scalar value 1, with the same size as input.
|
|
1458
|
-
* @param {Tensor} tensor The size of input will determine size of the output tensor.
|
|
1459
|
-
* @returns {Tensor} The ones tensor.
|
|
1460
|
-
*/
|
|
1461
|
-
export function ones_like(tensor) {
|
|
1462
|
-
return ones(tensor.dims);
|
|
1463
|
-
}
|
|
1464
|
-
|
|
1465
|
-
/**
|
|
1466
|
-
* Returns a tensor filled with the scalar value 0, with the shape defined by the variable argument size.
|
|
1467
|
-
* @param {number[]} size A sequence of integers defining the shape of the output tensor.
|
|
1468
|
-
* @returns {Tensor} The zeros tensor.
|
|
1469
|
-
*/
|
|
1470
|
-
export function zeros(size) {
|
|
1471
|
-
return fullHelper(size, 0n, 'int64', BigInt64Array);
|
|
1472
|
-
}
|
|
1473
|
-
|
|
1474
|
-
/**
|
|
1475
|
-
* Returns a tensor filled with the scalar value 0, with the same size as input.
|
|
1476
|
-
* @param {Tensor} tensor The size of input will determine size of the output tensor.
|
|
1477
|
-
* @returns {Tensor} The zeros tensor.
|
|
1478
|
-
*/
|
|
1479
|
-
export function zeros_like(tensor) {
|
|
1480
|
-
return zeros(tensor.dims);
|
|
1481
|
-
}
|
|
1482
|
-
|
|
1483
|
-
/**
|
|
1484
|
-
* Returns a tensor filled with random numbers from a uniform distribution on the interval [0, 1)
|
|
1485
|
-
* @param {number[]} size A sequence of integers defining the shape of the output tensor.
|
|
1486
|
-
* @returns {Tensor} The random tensor.
|
|
1487
|
-
*/
|
|
1488
|
-
export function rand(size) {
|
|
1489
|
-
const length = size.reduce((a, b) => a * b, 1);
|
|
1490
|
-
return new Tensor(
|
|
1491
|
-
"float32",
|
|
1492
|
-
Float32Array.from({ length }, () => Math.random()),
|
|
1493
|
-
size,
|
|
1494
|
-
)
|
|
1495
|
-
}
|
|
1496
|
-
|
|
1497
|
-
/**
|
|
1498
|
-
* Quantizes the embeddings tensor to binary or unsigned binary precision.
|
|
1499
|
-
* @param {Tensor} tensor The tensor to quantize.
|
|
1500
|
-
* @param {'binary'|'ubinary'} precision The precision to use for quantization.
|
|
1501
|
-
* @returns {Tensor} The quantized tensor.
|
|
1502
|
-
*/
|
|
1503
|
-
export function quantize_embeddings(tensor, precision) {
|
|
1504
|
-
if (tensor.dims.length !== 2) {
|
|
1505
|
-
throw new Error("The tensor must have 2 dimensions");
|
|
1506
|
-
}
|
|
1507
|
-
if (tensor.dims.at(-1) % 8 !== 0) {
|
|
1508
|
-
throw new Error("The last dimension of the tensor must be a multiple of 8");
|
|
1509
|
-
}
|
|
1510
|
-
if (!['binary', 'ubinary'].includes(precision)) {
|
|
1511
|
-
throw new Error("The precision must be either 'binary' or 'ubinary'");
|
|
1512
|
-
}
|
|
1513
|
-
|
|
1514
|
-
const signed = precision === 'binary';
|
|
1515
|
-
const dtype = signed ? 'int8' : 'uint8';
|
|
1516
|
-
|
|
1517
|
-
// Create a typed array to store the packed bits
|
|
1518
|
-
const cls = signed ? Int8Array : Uint8Array;
|
|
1519
|
-
const inputData = tensor.data;
|
|
1520
|
-
const outputData = new cls(inputData.length / 8);
|
|
1521
|
-
|
|
1522
|
-
// Iterate over each number in the array
|
|
1523
|
-
for (let i = 0; i < inputData.length; ++i) {
|
|
1524
|
-
// Determine if the number is greater than 0
|
|
1525
|
-
const bit = inputData[i] > 0 ? 1 : 0;
|
|
1526
|
-
|
|
1527
|
-
// Calculate the index in the typed array and the position within the byte
|
|
1528
|
-
const arrayIndex = Math.floor(i / 8);
|
|
1529
|
-
const bitPosition = i % 8;
|
|
1530
|
-
|
|
1531
|
-
// Pack the bit into the typed array
|
|
1532
|
-
outputData[arrayIndex] |= bit << (7 - bitPosition);
|
|
1533
|
-
if (signed && bitPosition === 0) {
|
|
1534
|
-
outputData[arrayIndex] -= 128;
|
|
1535
|
-
}
|
|
1536
|
-
};
|
|
1537
|
-
|
|
1538
|
-
return new Tensor(dtype, outputData, [tensor.dims[0], tensor.dims[1] / 8]);
|
|
1539
|
-
}
|