src/api/native_tensor_nn.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | #include "api_internal.h" | ||
| 2 | |||
| 3 | #include <cmath> | ||
| 4 | #include <cstdint> | ||
| 5 | #include <cstring> | ||
| 6 | #include <optional> | ||
| 7 | #include <span> | ||
| 8 | #include <stdexcept> | ||
| 9 | #include <string> | ||
| 10 | #include <vector> | ||
| 11 | |||
| 12 | namespace brotensor::api { | ||
| 13 | |||
| 14 | namespace { | ||
| 15 | |||
| 16 | namespace ev = bronze::embed; | ||
| 17 | using Value = bronze::Value; | ||
| 18 | using brotensor::Tensor; | ||
| 19 | using brotensor::Dtype; | ||
| 20 | |||
| 21 | 10 | int32_t toI32Trunc(Value v) { | |
| 22 | 10 | double d = ev::toDouble(v); | |
| 23 | 10 | return std::isfinite(d) ? static_cast<int32_t>(static_cast<int64_t>(d)) : 0; | |
| 24 | } | ||
| 25 | |||
| 26 | 2 | int32_t reqInt(Value v, const char* label, const char* name) { | |
| 27 | 2 | if (ev::isUndefined(v)) { | |
| 28 | ✗ | ev::throwTypeError(std::string(label) + ": " + name + " is required"); | |
| 29 | } | ||
| 30 | 2 | return toI32Trunc(v); | |
| 31 | ✗ | } | |
| 32 | |||
| 33 | ✗ | int32_t optInt(Value v, int32_t def) { | |
| 34 | ✗ | if (ev::isUndefined(v) || ev::isNull(v)) return def; | |
| 35 | ✗ | return toI32Trunc(v); | |
| 36 | ✗ | } | |
| 37 | |||
| 38 | 2 | double optNum(Value v, double def) { | |
| 39 | 2 | if (ev::isUndefined(v) || ev::isNull(v)) return def; | |
| 40 | 2 | return ev::toDouble(v); | |
| 41 | 2 | } | |
| 42 | |||
| 43 | 8 | void needRopeInput(const char* L, const Tensor* xt, int32_t headDim, int32_t numHeads) { | |
| 44 | 8 | needPositive(L, {headDim, numHeads}); | |
| 45 | 8 | if (headDim % 2 != 0) { | |
| 46 | 4 | setError(std::string(L) + ": headDim must be even"); | |
| 47 | } | ||
| 48 | 6 | if (static_cast<int64_t>(xt->cols) != static_cast<int64_t>(numHeads) * headDim) { | |
| 49 | 4 | setError(std::string(L) + ": X has " + std::to_string(xt->cols) + " columns, numHeads*headDim is " + | |
| 50 | 2 | std::to_string(static_cast<int64_t>(numHeads) * headDim)); | |
| 51 | } | ||
| 52 | 8 | } | |
| 53 | |||
| 54 | 2 | void needRopeTables(const char* L, const Tensor* xt, const Tensor* ct, const Tensor* st, int32_t headDim) { | |
| 55 | 2 | const int64_t n = elems({xt->rows, headDim / 2}); | |
| 56 | 2 | needElems(L, "cosTbl", ct, n); | |
| 57 | 2 | needElems(L, "sinTbl", st, n); | |
| 58 | 2 | if (ct->dtype != Dtype::FP32 || st->dtype != Dtype::FP32) { | |
| 59 | ✗ | setError(std::string(L) + ": cosTbl and sinTbl must be FP32"); | |
| 60 | } | ||
| 61 | 2 | } | |
| 62 | |||
| 63 | ✗ | void needDecodeShapes(const char* L, const Tensor* qt, const Tensor* kt, const Tensor* vt, | |
| 64 | int32_t numHeads, int32_t kvHeads) { | ||
| 65 | ✗ | needPositive(L, {numHeads, kvHeads}); | |
| 66 | ✗ | if (numHeads % kvHeads != 0 || qt->cols % numHeads != 0) { | |
| 67 | ✗ | setError(std::string(L) + ": numKvHeads must divide numHeads, and numHeads Q.cols"); | |
| 68 | } | ||
| 69 | ✗ | const int64_t headDim = qt->cols / numHeads; | |
| 70 | ✗ | if (kt->cols != kvHeads * headDim || vt->cols != kvHeads * headDim || vt->rows != kt->rows) { | |
| 71 | ✗ | setError(std::string(L) + ": K_cache/V_cache must both be (L_max, numKvHeads*headDim) with headDim = Q.cols/numHeads"); | |
| 72 | } | ||
| 73 | ✗ | needSameDtype(L, "K_cache", kt, qt); | |
| 74 | ✗ | needSameDtype(L, "V_cache", vt, qt); | |
| 75 | ✗ | } | |
| 76 | |||
| 77 | // Run outside BROTENSOR_API_TRY for type/size checks, then inside BROTENSOR_API_TRY | ||
| 78 | // for device->host copy and range check (throwing std::runtime_error). | ||
| 79 | 20 | void validateEmbeddingArgs(const char* L, const Tensor* it, int32_t B) { | |
| 80 | 20 | if (B <= 0) { | |
| 81 | ✗ | setError(std::string(L) + ": B must be positive"); | |
| 82 | } | ||
| 83 | 20 | needElems(L, "indices", it, B); | |
| 84 | 20 | if (it->dtype != Dtype::INT32 && it->dtype != Dtype::FP32) { | |
| 85 | ✗ | setError(std::string(L) + ": indices must be INT32 storage or FP32 values"); | |
| 86 | } | ||
| 87 | 20 | } | |
| 88 | |||
| 89 | 18 | Tensor buildEmbeddingDeviceIdx(const Tensor& it, int32_t B, int32_t V, brotensor::Device dev) { | |
| 90 | 18 | std::vector<int32_t> idx(static_cast<size_t>(B)); | |
| 91 | 18 | auto host = it.to(brotensor::Device::CPU); | |
| 92 | 18 | if (it.dtype == Dtype::INT32) { | |
| 93 | 12 | std::memcpy(idx.data(), host.host_raw(), idx.size() * sizeof(int32_t)); | |
| 94 | 12 | } else { | |
| 95 | 6 | const float* f = host.host_f32(); | |
| 96 | 16 | for (int32_t i = 0; i < B; ++i) idx[i] = static_cast<int32_t>(f[i]); | |
| 97 | } | ||
| 98 | 38 | for (int32_t i = 0; i < B; ++i) { | |
| 99 | 24 | if (idx[i] < 0 || idx[i] >= V) { | |
| 100 | 8 | throw std::runtime_error("index " + std::to_string(idx[i]) + " at " + std::to_string(i) + | |
| 101 | 4 | " is outside the table's " + std::to_string(V) + " rows"); | |
| 102 | } | ||
| 103 | 20 | } | |
| 104 | 14 | return Tensor::from_raw_bytes_on(dev, idx.data(), B, 1, Dtype::INT32, idx.size() * sizeof(int32_t)); | |
| 105 | 22 | } | |
| 106 | |||
| 107 | 6 | std::vector<const Tensor*> asConst(const std::vector<Tensor*>& v) { | |
| 108 | 6 | return std::vector<const Tensor*>(v.begin(), v.end()); | |
| 109 | } | ||
| 110 | |||
| 111 | 12 | void needOneDtype(const char* L, const std::vector<Tensor*>& parts, const Tensor* ref) { | |
| 112 | 34 | for (const Tensor* p : parts) { | |
| 113 | 22 | needSameDtype(L, "every part", p, ref); | |
| 114 | } | ||
| 115 | 12 | } | |
| 116 | |||
| 117 | 20 | void needFp32Out(const char* L, const Tensor* y) { | |
| 118 | 20 | if (y->dtype != Dtype::FP32) { | |
| 119 | ✗ | setError(std::string(L) + ": Y must be FP32"); | |
| 120 | } | ||
| 121 | 20 | } | |
| 122 | |||
| 123 | 4 | std::vector<int> readChannelCounts(Value v, const char* L) { | |
| 124 | 4 | ev::TypedArrayInfo ta = ev::typedArrayInfo(v); | |
| 125 | 4 | if (ta.data && ta.elementKind == ev::elements::Int32) { | |
| 126 | ✗ | const int32_t* p = reinterpret_cast<const int32_t*>(ta.data); | |
| 127 | ✗ | return std::vector<int>(p, p + ta.elementCount); | |
| 128 | } | ||
| 129 | 4 | if (!ev::isObject(v) || ev::isTypedArray(v) || ev::isFunction(v)) { | |
| 130 | ✗ | ev::throwTypeError(std::string(L) + ": C_per_part must be an array of ints"); | |
| 131 | } | ||
| 132 | 4 | ev::Persistent arr(v); | |
| 133 | 4 | Value lenV = ev::getProperty(arr.get(), "length"); | |
| 134 | 4 | if (!ev::isNumber(lenV)) { | |
| 135 | ✗ | ev::throwTypeError(std::string(L) + ": C_per_part must be an array of ints"); | |
| 136 | } | ||
| 137 | 4 | double lenD = ev::toDouble(lenV); | |
| 138 | 4 | if (!std::isfinite(lenD) || lenD < 0.0 || lenD > 4294967295.0) { | |
| 139 | ✗ | ev::throwRangeError(std::string(L) + ": invalid C_per_part length"); | |
| 140 | } | ||
| 141 | 4 | uint32_t n = static_cast<uint32_t>(lenD); | |
| 142 | 4 | std::vector<int> out; | |
| 143 | 4 | out.reserve(n); | |
| 144 | 12 | for (uint32_t i = 0; i < n; ++i) { | |
| 145 | 8 | out.push_back(toI32Trunc(ev::getElement(arr.get(), i))); | |
| 146 | 8 | } | |
| 147 | 4 | return out; | |
| 148 | 4 | } | |
| 149 | |||
| 150 | // ---- layernorm / norm / rope / modulate ------------------------------------ | ||
| 151 | |||
| 152 | 2 | Value nnLayernormForward(GpuTensorHandle* x, GpuTensorHandle* gamma, GpuTensorHandle* beta, | |
| 153 | GpuTensorHandle* y, GpuTensorHandle* xhat, std::optional<Value> epsV) { | ||
| 154 | 2 | const char* L = "layernormForward"; | |
| 155 | 2 | Tensor* xt = &x->tensor; | |
| 156 | 2 | Tensor* gt = &gamma->tensor; | |
| 157 | 2 | Tensor* bt = &beta->tensor; | |
| 158 | 2 | Tensor* yt = &y->tensor; | |
| 159 | 2 | Tensor* xht = &xhat->tensor; | |
| 160 | 2 | needPair(L, "gamma", gt, xt); | |
| 161 | 2 | needPair(L, "beta", bt, xt); | |
| 162 | 2 | const double eps = epsV ? optNum(*epsV, 0.00001) : 0.00001; | |
| 163 | 2 | float mean = 0.f, rstd = 0.f; | |
| 164 | 2 | BROTENSOR_API_TRY | |
| 165 | 2 | brotensor::layernorm_forward(*xt, *gt, *bt, *yt, *xht, mean, rstd, static_cast<float>(eps)); | |
| 166 | 2 | BROTENSOR_API_CATCH(L) | |
| 167 | 2 | ev::ObjectBuilder res; | |
| 168 | 2 | res.set("mean", static_cast<double>(mean)); | |
| 169 | 2 | res.set("rstd", static_cast<double>(rstd)); | |
| 170 | 2 | return res.build(); | |
| 171 | 2 | } | |
| 172 | |||
| 173 | ✗ | void nnLayernormBackward(GpuTensorHandle* dY, GpuTensorHandle* xhat, GpuTensorHandle* gamma, | |
| 174 | double rstd, GpuTensorHandle* dX, GpuTensorHandle* dGamma, GpuTensorHandle* dBeta) { | ||
| 175 | ✗ | const char* L = "layernormBackward"; | |
| 176 | ✗ | Tensor* dyt = &dY->tensor; | |
| 177 | ✗ | Tensor* xht = &xhat->tensor; | |
| 178 | ✗ | Tensor* gt = &gamma->tensor; | |
| 179 | ✗ | Tensor* dxt = &dX->tensor; | |
| 180 | ✗ | Tensor* dgt = &dGamma->tensor; | |
| 181 | ✗ | Tensor* dbt = &dBeta->tensor; | |
| 182 | ✗ | needPair(L, "xhat", xht, dyt); | |
| 183 | ✗ | needPair(L, "gamma", gt, dyt); | |
| 184 | ✗ | needElems(L, "dGamma", dgt, dyt->size()); | |
| 185 | ✗ | needElems(L, "dBeta", dbt, dyt->size()); | |
| 186 | ✗ | needSameDtype(L, "dGamma", dgt, dyt); | |
| 187 | ✗ | needSameDtype(L, "dBeta", dbt, dyt); | |
| 188 | ✗ | BROTENSOR_API_TRY | |
| 189 | ✗ | brotensor::layernorm_backward(*dyt, *xht, *gt, static_cast<float>(rstd), *dxt, *dgt, *dbt); | |
| 190 | ✗ | BROTENSOR_API_CATCH(L) | |
| 191 | ✗ | } | |
| 192 | |||
| 193 | ✗ | void nnLayernormForwardInferenceBatched(GpuTensorHandle* X_RD, GpuTensorHandle* gamma, GpuTensorHandle* beta, | |
| 194 | GpuTensorHandle* Y_RD, std::optional<Value> epsV) { | ||
| 195 | ✗ | const char* L = "layernormForwardInferenceBatched"; | |
| 196 | ✗ | Tensor* xt = &X_RD->tensor; | |
| 197 | ✗ | Tensor* gt = &gamma->tensor; | |
| 198 | ✗ | Tensor* bt = &beta->tensor; | |
| 199 | ✗ | Tensor* yt = &Y_RD->tensor; | |
| 200 | ✗ | needElems(L, "gamma", gt, xt->cols); | |
| 201 | ✗ | needElems(L, "beta", bt, xt->cols); | |
| 202 | ✗ | needSameDtype(L, "gamma", gt, xt); | |
| 203 | ✗ | needSameDtype(L, "beta", bt, xt); | |
| 204 | ✗ | const double eps = epsV ? optNum(*epsV, 0.00001) : 0.00001; | |
| 205 | ✗ | BROTENSOR_API_TRY | |
| 206 | ✗ | brotensor::layernorm_forward_inference_batched(*xt, *gt, *bt, *yt, static_cast<float>(eps)); | |
| 207 | ✗ | BROTENSOR_API_CATCH(L) | |
| 208 | ✗ | } | |
| 209 | |||
| 210 | ✗ | void nnLayernormForwardInferenceBatchedFp16(GpuTensorHandle* X_RD, GpuTensorHandle* gamma, GpuTensorHandle* beta, | |
| 211 | GpuTensorHandle* Y_RD, std::optional<Value> epsV) { | ||
| 212 | ✗ | const char* L = "layernormForwardInferenceBatchedFp16"; | |
| 213 | ✗ | Tensor* xt = &X_RD->tensor; | |
| 214 | ✗ | Tensor* gt = &gamma->tensor; | |
| 215 | ✗ | Tensor* bt = &beta->tensor; | |
| 216 | ✗ | Tensor* yt = &Y_RD->tensor; | |
| 217 | ✗ | needElems(L, "gamma", gt, xt->cols); | |
| 218 | ✗ | needElems(L, "beta", bt, xt->cols); | |
| 219 | ✗ | needSameDtype(L, "gamma", gt, xt); | |
| 220 | ✗ | needSameDtype(L, "beta", bt, xt); | |
| 221 | ✗ | const double eps = epsV ? optNum(*epsV, 0.00001) : 0.00001; | |
| 222 | ✗ | BROTENSOR_API_TRY | |
| 223 | ✗ | brotensor::layernorm_forward_inference_batched_fp16(*xt, *gt, *bt, *yt, static_cast<float>(eps)); | |
| 224 | ✗ | BROTENSOR_API_CATCH(L) | |
| 225 | ✗ | } | |
| 226 | |||
| 227 | ✗ | void nnRmsNormForward(GpuTensorHandle* X, GpuTensorHandle* gamma, double eps, GpuTensorHandle* Y) { | |
| 228 | ✗ | const char* L = "rmsNormForward"; | |
| 229 | ✗ | Tensor* xt = &X->tensor; | |
| 230 | ✗ | Tensor* gt = &gamma->tensor; | |
| 231 | ✗ | needElems(L, "gamma", gt, xt->cols); | |
| 232 | ✗ | if (gt->dtype != Dtype::FP32) needSameDtype(L, "gamma", gt, xt); | |
| 233 | ✗ | BROTENSOR_API_TRY | |
| 234 | ✗ | brotensor::rms_norm_forward(*xt, *gt, static_cast<float>(eps), Y->tensor); | |
| 235 | ✗ | BROTENSOR_API_CATCH(L) | |
| 236 | ✗ | } | |
| 237 | |||
| 238 | ✗ | void nnRmsNormBackward(GpuTensorHandle* X, GpuTensorHandle* gamma, GpuTensorHandle* dY, | |
| 239 | double eps, GpuTensorHandle* dX, GpuTensorHandle* dGamma) { | ||
| 240 | ✗ | const char* L = "rmsNormBackward"; | |
| 241 | ✗ | Tensor* xt = &X->tensor; | |
| 242 | ✗ | Tensor* gt = &gamma->tensor; | |
| 243 | ✗ | Tensor* dyt = &dY->tensor; | |
| 244 | ✗ | Tensor* dgt = &dGamma->tensor; | |
| 245 | ✗ | needElems(L, "gamma", gt, xt->cols); | |
| 246 | ✗ | needSameDtype(L, "gamma", gt, xt); | |
| 247 | ✗ | needPair(L, "dY", dyt, xt); | |
| 248 | ✗ | needElems(L, "dGamma", dgt, xt->cols); | |
| 249 | ✗ | needSameDtype(L, "dGamma", dgt, xt); | |
| 250 | ✗ | BROTENSOR_API_TRY | |
| 251 | ✗ | brotensor::rms_norm_backward(*xt, *gt, *dyt, static_cast<float>(eps), dX->tensor, *dgt); | |
| 252 | ✗ | BROTENSOR_API_CATCH(L) | |
| 253 | ✗ | } | |
| 254 | |||
| 255 | 2 | void nnGroupNormForward(GpuTensorHandle* X, GpuTensorHandle* gamma, GpuTensorHandle* beta, | |
| 256 | int32_t N, int32_t C, int32_t H, int32_t W, int32_t numGroups, | ||
| 257 | double eps, GpuTensorHandle* Y) { | ||
| 258 | 2 | const char* L = "groupNormForward"; | |
| 259 | 2 | Tensor* xt = &X->tensor; | |
| 260 | 2 | Tensor* gt = &gamma->tensor; | |
| 261 | 2 | Tensor* bt = &beta->tensor; | |
| 262 | 2 | needPositive(L, {numGroups}); | |
| 263 | 2 | needNonNegative(L, {N, C, H, W}); | |
| 264 | 2 | if (C % numGroups != 0) setError("groupNormForward: numGroups must divide C"); | |
| 265 | ✗ | needElems(L, "X", xt, elems({N, C, H, W})); | |
| 266 | ✗ | needElems(L, "gamma", gt, C); | |
| 267 | ✗ | needElems(L, "beta", bt, C); | |
| 268 | ✗ | needSameDtype(L, "gamma", gt, xt); | |
| 269 | ✗ | needSameDtype(L, "beta", bt, xt); | |
| 270 | ✗ | BROTENSOR_API_TRY | |
| 271 | ✗ | brotensor::group_norm_forward(*xt, *gt, *bt, N, C, H, W, numGroups, static_cast<float>(eps), Y->tensor); | |
| 272 | ✗ | BROTENSOR_API_CATCH(L) | |
| 273 | 2 | } | |
| 274 | |||
| 275 | ✗ | void nnGroupNormBackward(GpuTensorHandle* X, GpuTensorHandle* gamma, GpuTensorHandle* dY, | |
| 276 | int32_t N, int32_t C, int32_t H, int32_t W, int32_t numGroups, | ||
| 277 | double eps, GpuTensorHandle* dX, GpuTensorHandle* dGamma, GpuTensorHandle* dBeta) { | ||
| 278 | ✗ | const char* L = "groupNormBackward"; | |
| 279 | ✗ | Tensor* xt = &X->tensor; | |
| 280 | ✗ | Tensor* gt = &gamma->tensor; | |
| 281 | ✗ | Tensor* dyt = &dY->tensor; | |
| 282 | ✗ | Tensor* dgt = &dGamma->tensor; | |
| 283 | ✗ | Tensor* dbt = &dBeta->tensor; | |
| 284 | ✗ | needPositive(L, {numGroups}); | |
| 285 | ✗ | needNonNegative(L, {N, C, H, W}); | |
| 286 | ✗ | if (C % numGroups != 0) setError("groupNormBackward: numGroups must divide C"); | |
| 287 | ✗ | const int64_t n = elems({N, C, H, W}); | |
| 288 | ✗ | needElems(L, "X", xt, n); | |
| 289 | ✗ | needElems(L, "dY", dyt, n); | |
| 290 | ✗ | needSameDtype(L, "dY", dyt, xt); | |
| 291 | ✗ | for (const Tensor* t : {gt, dgt, dbt}) { | |
| 292 | ✗ | needElems(L, "gamma/dGamma/dBeta", t, C); | |
| 293 | ✗ | needSameDtype(L, "gamma/dGamma/dBeta", t, xt); | |
| 294 | } | ||
| 295 | ✗ | BROTENSOR_API_TRY | |
| 296 | ✗ | brotensor::group_norm_backward(*xt, *gt, *dyt, N, C, H, W, numGroups, static_cast<float>(eps), | |
| 297 | ✗ | dX->tensor, *dgt, *dbt); | |
| 298 | ✗ | BROTENSOR_API_CATCH(L) | |
| 299 | ✗ | } | |
| 300 | |||
| 301 | ✗ | void nnRopeForward(GpuTensorHandle* X, int32_t headDim, int32_t numHeads, int32_t seqOffset, | |
| 302 | double thetaBase, GpuTensorHandle* Y) { | ||
| 303 | ✗ | const char* L = "ropeForward"; | |
| 304 | ✗ | needRopeInput(L, &X->tensor, headDim, numHeads); | |
| 305 | ✗ | BROTENSOR_API_TRY | |
| 306 | ✗ | brotensor::rope_forward(X->tensor, headDim, numHeads, seqOffset, static_cast<float>(thetaBase), Y->tensor); | |
| 307 | ✗ | BROTENSOR_API_CATCH(L) | |
| 308 | ✗ | } | |
| 309 | |||
| 310 | ✗ | void nnRopeBackward(GpuTensorHandle* dY, int32_t headDim, int32_t numHeads, int32_t seqOffset, | |
| 311 | double thetaBase, GpuTensorHandle* dX) { | ||
| 312 | ✗ | const char* L = "ropeBackward"; | |
| 313 | ✗ | needRopeInput(L, &dY->tensor, headDim, numHeads); | |
| 314 | ✗ | BROTENSOR_API_TRY | |
| 315 | ✗ | brotensor::rope_backward(dY->tensor, headDim, numHeads, seqOffset, static_cast<float>(thetaBase), dX->tensor); | |
| 316 | ✗ | BROTENSOR_API_CATCH(L) | |
| 317 | ✗ | } | |
| 318 | |||
| 319 | 2 | void nnRopeApply(GpuTensorHandle* X, GpuTensorHandle* cosTbl, GpuTensorHandle* sinTbl, | |
| 320 | int32_t headDim, int32_t numHeads, GpuTensorHandle* Y) { | ||
| 321 | 2 | const char* L = "ropeApply"; | |
| 322 | 2 | needRopeInput(L, &X->tensor, headDim, numHeads); | |
| 323 | 2 | needRopeTables(L, &X->tensor, &cosTbl->tensor, &sinTbl->tensor, headDim); | |
| 324 | 2 | BROTENSOR_API_TRY | |
| 325 | 2 | brotensor::rope_apply(X->tensor, cosTbl->tensor, sinTbl->tensor, headDim, numHeads, Y->tensor); | |
| 326 | 2 | BROTENSOR_API_CATCH(L) | |
| 327 | 2 | } | |
| 328 | |||
| 329 | ✗ | void nnRopeApplyBackward(GpuTensorHandle* dY, GpuTensorHandle* cosTbl, GpuTensorHandle* sinTbl, | |
| 330 | int32_t headDim, int32_t numHeads, GpuTensorHandle* dX) { | ||
| 331 | ✗ | const char* L = "ropeApplyBackward"; | |
| 332 | ✗ | needRopeInput(L, &dY->tensor, headDim, numHeads); | |
| 333 | ✗ | needRopeTables(L, &dY->tensor, &cosTbl->tensor, &sinTbl->tensor, headDim); | |
| 334 | ✗ | BROTENSOR_API_TRY | |
| 335 | ✗ | brotensor::rope_apply_backward(dY->tensor, cosTbl->tensor, sinTbl->tensor, headDim, numHeads, dX->tensor); | |
| 336 | ✗ | BROTENSOR_API_CATCH(L) | |
| 337 | ✗ | } | |
| 338 | |||
| 339 | ✗ | void nnModulate(GpuTensorHandle* X, GpuTensorHandle* scale, GpuTensorHandle* shift, GpuTensorHandle* Y) { | |
| 340 | ✗ | const char* L = "modulate"; | |
| 341 | ✗ | Tensor* xt = &X->tensor; | |
| 342 | ✗ | Tensor* st = &scale->tensor; | |
| 343 | ✗ | Tensor* sht = &shift->tensor; | |
| 344 | ✗ | needElems(L, "scale", st, xt->cols); | |
| 345 | ✗ | needElems(L, "shift", sht, xt->cols); | |
| 346 | ✗ | needSameDtype(L, "scale", st, xt); | |
| 347 | ✗ | needSameDtype(L, "shift", sht, xt); | |
| 348 | ✗ | BROTENSOR_API_TRY | |
| 349 | ✗ | brotensor::modulate(*xt, *st, *sht, Y->tensor); | |
| 350 | ✗ | BROTENSOR_API_CATCH(L) | |
| 351 | ✗ | } | |
| 352 | |||
| 353 | ✗ | void nnBroadcastMul(GpuTensorHandle* X, GpuTensorHandle* v, GpuTensorHandle* Y) { | |
| 354 | ✗ | const char* L = "broadcastMul"; | |
| 355 | ✗ | Tensor* xt = &X->tensor; | |
| 356 | ✗ | Tensor* vt = &v->tensor; | |
| 357 | ✗ | needElems(L, "v", vt, xt->cols); | |
| 358 | ✗ | needSameDtype(L, "v", vt, xt); | |
| 359 | ✗ | BROTENSOR_API_TRY | |
| 360 | ✗ | brotensor::broadcast_mul(*xt, *vt, Y->tensor); | |
| 361 | ✗ | BROTENSOR_API_CATCH(L) | |
| 362 | ✗ | } | |
| 363 | |||
| 364 | ✗ | void nnAttentionTokenMoments(GpuTensorHandle* Attn, int32_t h_lat, int32_t w_lat, | |
| 365 | GpuTensorHandle* mass, GpuTensorHandle* centroid) { | ||
| 366 | ✗ | const char* L = "attentionTokenMoments"; | |
| 367 | ✗ | needPositive(L, {h_lat, w_lat}); | |
| 368 | ✗ | if (static_cast<int64_t>(Attn->tensor.rows) != static_cast<int64_t>(h_lat) * w_lat) { | |
| 369 | ✗ | setError("attentionTokenMoments: Attn.rows must equal h_lat*w_lat"); | |
| 370 | } | ||
| 371 | ✗ | BROTENSOR_API_TRY | |
| 372 | ✗ | brotensor::attention_token_moments(Attn->tensor, h_lat, w_lat, mass->tensor, centroid->tensor); | |
| 373 | ✗ | BROTENSOR_API_CATCH(L) | |
| 374 | ✗ | } | |
| 375 | |||
| 376 | ✗ | void nnBuildSlotMask(GpuTensorHandle* x, int32_t offset, int32_t K, int32_t stride, GpuTensorHandle* mask) { | |
| 377 | ✗ | const char* L = "buildSlotMask"; | |
| 378 | ✗ | Tensor* xt = &x->tensor; | |
| 379 | ✗ | needNonNegative(L, {offset, K, stride}); | |
| 380 | ✗ | if (K > 0) { | |
| 381 | ✗ | needElems(L, "x", xt, static_cast<int64_t>(offset) + static_cast<int64_t>(K - 1) * stride + 1); | |
| 382 | ✗ | } | |
| 383 | ✗ | if (xt->dtype != Dtype::FP32) setError("buildSlotMask: x must be FP32"); | |
| 384 | ✗ | BROTENSOR_API_TRY | |
| 385 | ✗ | brotensor::build_slot_mask(*xt, offset, K, stride, mask->tensor); | |
| 386 | ✗ | BROTENSOR_API_CATCH(L) | |
| 387 | ✗ | } | |
| 388 | |||
| 389 | ✗ | void nnBuildCausalMaskRow(int32_t L_, int32_t q, GpuTensorHandle* mask) { | |
| 390 | ✗ | needNonNegative("buildCausalMaskRow", {L_}); | |
| 391 | ✗ | BROTENSOR_API_TRY | |
| 392 | ✗ | brotensor::build_causal_mask_row(L_, q, mask->tensor); | |
| 393 | ✗ | BROTENSOR_API_CATCH("buildCausalMaskRow") | |
| 394 | ✗ | } | |
| 395 | |||
| 396 | // ---- decode attention / kv cache / embedding / optimisers ------------------ | ||
| 397 | |||
| 398 | ✗ | void nnFlashAttentionDecode(GpuTensorHandle* Q, GpuTensorHandle* K_cache, GpuTensorHandle* V_cache, | |
| 399 | Value validLenV, Value numHeadsV, GpuTensorHandle* O, | ||
| 400 | std::optional<Value> numKvHeadsV, std::optional<Value> attnSoftcapV, | ||
| 401 | std::optional<Value> windowV) { | ||
| 402 | ✗ | const char* L = "flashAttentionDecode"; | |
| 403 | ✗ | const int32_t validLen = reqInt(validLenV, L, "validLen"); | |
| 404 | ✗ | const int32_t numHeads = reqInt(numHeadsV, L, "numHeads"); | |
| 405 | ✗ | Tensor* qt = &Q->tensor; | |
| 406 | ✗ | Tensor* kt = &K_cache->tensor; | |
| 407 | ✗ | Tensor* vt = &V_cache->tensor; | |
| 408 | ✗ | const int32_t numKvHeads = numKvHeadsV ? optInt(*numKvHeadsV, 0) : 0; | |
| 409 | ✗ | const int32_t kvHeads = (numKvHeads > 0) ? numKvHeads : numHeads; | |
| 410 | ✗ | const double attnSoftcap = attnSoftcapV ? optNum(*attnSoftcapV, 0.0) : 0.0; | |
| 411 | ✗ | const int32_t window = windowV ? optInt(*windowV, 0) : 0; | |
| 412 | ✗ | needDecodeShapes(L, qt, kt, vt, numHeads, kvHeads); | |
| 413 | ✗ | if (validLen < qt->rows || validLen > kt->rows) { | |
| 414 | ✗ | setError("flashAttentionDecode: validLen must lie in [Q.rows, K_cache.rows]"); | |
| 415 | } | ||
| 416 | ✗ | BROTENSOR_API_TRY | |
| 417 | ✗ | brotensor::flash_attention_decode(*qt, *kt, *vt, validLen, numHeads, kvHeads, | |
| 418 | ✗ | O->tensor, static_cast<float>(attnSoftcap), window); | |
| 419 | ✗ | BROTENSOR_API_CATCH(L) | |
| 420 | ✗ | } | |
| 421 | |||
| 422 | ✗ | void nnFlashAttentionDecodeMasked(GpuTensorHandle* Q, GpuTensorHandle* K_cache, GpuTensorHandle* V_cache, | |
| 423 | GpuTensorHandle* dMask, Value numHeadsV, GpuTensorHandle* O, | ||
| 424 | std::optional<Value> numKvHeadsV, std::optional<Value> attnSoftcapV, | ||
| 425 | std::optional<Value> windowV) { | ||
| 426 | ✗ | const char* L = "flashAttentionDecodeMasked"; | |
| 427 | ✗ | const int32_t numHeads = reqInt(numHeadsV, L, "numHeads"); | |
| 428 | ✗ | Tensor* qt = &Q->tensor; | |
| 429 | ✗ | Tensor* kt = &K_cache->tensor; | |
| 430 | ✗ | Tensor* vt = &V_cache->tensor; | |
| 431 | ✗ | Tensor* mt = &dMask->tensor; | |
| 432 | ✗ | const int32_t numKvHeads = numKvHeadsV ? optInt(*numKvHeadsV, 0) : 0; | |
| 433 | ✗ | const int32_t kvHeads = (numKvHeads > 0) ? numKvHeads : numHeads; | |
| 434 | ✗ | const double attnSoftcap = attnSoftcapV ? optNum(*attnSoftcapV, 0.0) : 0.0; | |
| 435 | ✗ | const int32_t window = windowV ? optInt(*windowV, 0) : 0; | |
| 436 | ✗ | needDecodeShapes(L, qt, kt, vt, numHeads, kvHeads); | |
| 437 | ✗ | if (qt->rows != 1) setError("flashAttentionDecodeMasked: Q must be a single row"); | |
| 438 | ✗ | needMask(L, mt, kt->rows); | |
| 439 | ✗ | BROTENSOR_API_TRY | |
| 440 | ✗ | brotensor::flash_attention_decode_masked(*qt, *kt, *vt, static_cast<const float*>(mt->data), | |
| 441 | ✗ | numHeads, kvHeads, O->tensor, | |
| 442 | ✗ | static_cast<float>(attnSoftcap), window); | |
| 443 | ✗ | BROTENSOR_API_CATCH(L) | |
| 444 | ✗ | } | |
| 445 | |||
| 446 | ✗ | void nnKvCacheAppend(GpuTensorHandle* K_new, GpuTensorHandle* V_new, int32_t curLen, | |
| 447 | GpuTensorHandle* K_cache, GpuTensorHandle* V_cache) { | ||
| 448 | ✗ | const char* L = "kvCacheAppend"; | |
| 449 | ✗ | Tensor* knt = &K_new->tensor; | |
| 450 | ✗ | Tensor* vnt = &V_new->tensor; | |
| 451 | ✗ | Tensor* kct = &K_cache->tensor; | |
| 452 | ✗ | Tensor* vct = &V_cache->tensor; | |
| 453 | ✗ | needNonNegative(L, {curLen}); | |
| 454 | ✗ | if (vnt->rows != knt->rows || vnt->cols != knt->cols || kct->cols != knt->cols || vct->cols != knt->cols) { | |
| 455 | ✗ | setError("kvCacheAppend: K_new/V_new/K_cache/V_cache must share a column count, K_new and V_new a shape"); | |
| 456 | } | ||
| 457 | ✗ | const int64_t end = static_cast<int64_t>(curLen) + knt->rows; | |
| 458 | ✗ | if (end > kct->rows || end > vct->rows) { | |
| 459 | ✗ | setError("kvCacheAppend: curLen + K_new.rows exceeds the cache's rows"); | |
| 460 | } | ||
| 461 | ✗ | for (const Tensor* t : {vnt, kct, vct}) { | |
| 462 | ✗ | needSameDtype(L, "every operand", t, knt); | |
| 463 | } | ||
| 464 | ✗ | BROTENSOR_API_TRY | |
| 465 | ✗ | brotensor::kv_cache_append(*knt, *vnt, curLen, *kct, *vct); | |
| 466 | ✗ | BROTENSOR_API_CATCH(L) | |
| 467 | ✗ | } | |
| 468 | |||
| 469 | 18 | void nnEmbeddingLookupForward(GpuTensorHandle* table, GpuTensorHandle* idxAsInt32, int32_t B, | |
| 470 | GpuTensorHandle* out) { | ||
| 471 | 18 | const char* L = "embeddingLookupForward"; | |
| 472 | 18 | Tensor* tt = &table->tensor; | |
| 473 | 18 | Tensor* it = &idxAsInt32->tensor; | |
| 474 | 18 | validateEmbeddingArgs(L, it, B); | |
| 475 | 18 | BROTENSOR_API_TRY | |
| 476 | 18 | Tensor idx = buildEmbeddingDeviceIdx(*it, B, tt->rows, tt->device); | |
| 477 | 14 | brotensor::embedding_lookup_forward(*tt, static_cast<const int32_t*>(idx.data), B, out->tensor); | |
| 478 | 22 | BROTENSOR_API_CATCH(L) | |
| 479 | 22 | } | |
| 480 | |||
| 481 | ✗ | void nnEmbeddingLookupBackward(GpuTensorHandle* dOut, GpuTensorHandle* idxAsInt32, int32_t B, | |
| 482 | GpuTensorHandle* dTable) { | ||
| 483 | ✗ | const char* L = "embeddingLookupBackward"; | |
| 484 | ✗ | Tensor* dot = &dOut->tensor; | |
| 485 | ✗ | Tensor* it = &idxAsInt32->tensor; | |
| 486 | ✗ | Tensor* dtt = &dTable->tensor; | |
| 487 | ✗ | validateEmbeddingArgs(L, it, B); | |
| 488 | ✗ | needElems(L, "dOut", dot, elems({B, dtt->cols})); | |
| 489 | ✗ | needSameDtype(L, "dOut", dot, dtt); | |
| 490 | ✗ | BROTENSOR_API_TRY | |
| 491 | ✗ | Tensor idx = buildEmbeddingDeviceIdx(*it, B, dtt->rows, dtt->device); | |
| 492 | ✗ | brotensor::embedding_lookup_backward(*dot, static_cast<const int32_t*>(idx.data), B, *dtt); | |
| 493 | ✗ | BROTENSOR_API_CATCH(L) | |
| 494 | ✗ | } | |
| 495 | |||
| 496 | ✗ | void nnSgdStep(GpuTensorHandle* param, GpuTensorHandle* grad, GpuTensorHandle* velocity, | |
| 497 | double lr, double momentum) { | ||
| 498 | ✗ | const char* L = "sgdStep"; | |
| 499 | ✗ | Tensor* pt = ¶m->tensor; | |
| 500 | ✗ | Tensor* gt = &grad->tensor; | |
| 501 | ✗ | Tensor* vt = &velocity->tensor; | |
| 502 | ✗ | needPair(L, "grad", gt, pt); | |
| 503 | ✗ | needPair(L, "velocity", vt, pt); | |
| 504 | ✗ | if (pt->dtype != Dtype::FP32) setError("sgdStep: tensors must be FP32"); | |
| 505 | ✗ | BROTENSOR_API_TRY | |
| 506 | ✗ | brotensor::sgd_step(*pt, *gt, *vt, static_cast<float>(lr), static_cast<float>(momentum)); | |
| 507 | ✗ | BROTENSOR_API_CATCH(L) | |
| 508 | ✗ | } | |
| 509 | |||
| 510 | ✗ | void nnAdamStep(GpuTensorHandle* param, GpuTensorHandle* grad, GpuTensorHandle* m, GpuTensorHandle* v, | |
| 511 | double lr, double beta1, double beta2, double eps, int32_t step) { | ||
| 512 | ✗ | const char* L = "adamStep"; | |
| 513 | ✗ | Tensor* pt = ¶m->tensor; | |
| 514 | ✗ | Tensor* gt = &grad->tensor; | |
| 515 | ✗ | Tensor* mt = &m->tensor; | |
| 516 | ✗ | Tensor* vt = &v->tensor; | |
| 517 | ✗ | needPair(L, "grad", gt, pt); | |
| 518 | ✗ | needPair(L, "m", mt, pt); | |
| 519 | ✗ | needPair(L, "v", vt, pt); | |
| 520 | ✗ | if (step < 1) setError("adamStep: step is the 1-based bias-correction counter"); | |
| 521 | ✗ | if (pt->dtype != Dtype::FP32) setError("adamStep: tensors must be FP32"); | |
| 522 | ✗ | BROTENSOR_API_TRY | |
| 523 | ✗ | brotensor::adam_step(*pt, *gt, *mt, *vt, static_cast<float>(lr), static_cast<float>(beta1), | |
| 524 | ✗ | static_cast<float>(beta2), static_cast<float>(eps), step); | |
| 525 | ✗ | BROTENSOR_API_CATCH(L) | |
| 526 | ✗ | } | |
| 527 | |||
| 528 | // ---- cast / pool / losses / concat / RNG ----------------------------------- | ||
| 529 | |||
| 530 | 110 | void nnCast(GpuTensorHandle* src, GpuTensorHandle* dst, std::optional<Value> outDtype) { | |
| 531 | 110 | Dtype dt = outDtype ? parseDtypeValue(*outDtype, Dtype::FP32, "cast") : Dtype::FP32; | |
| 532 | 110 | BROTENSOR_API_TRY | |
| 533 | 110 | brotensor::cast(src->tensor, dst->tensor, dt); | |
| 534 | 110 | BROTENSOR_API_CATCH("cast") | |
| 535 | 110 | } | |
| 536 | |||
| 537 | 4 | void nnMaskedMeanPoolForward(GpuTensorHandle* X, ev::Nullable<GpuTensorHandle> mask, GpuTensorHandle* y) { | |
| 538 | 4 | const char* L = "maskedMeanPoolForward"; | |
| 539 | 4 | Tensor* mt = mask.ptr ? &mask.ptr->tensor : nullptr; | |
| 540 | 4 | needMask(L, mt, X->tensor.rows); | |
| 541 | 4 | BROTENSOR_API_TRY | |
| 542 | 4 | brotensor::masked_mean_pool_forward(X->tensor, maskPtr(mt), y->tensor); | |
| 543 | 4 | BROTENSOR_API_CATCH(L) | |
| 544 | 4 | } | |
| 545 | |||
| 546 | 2 | void nnMaskedMeanPoolBackward(GpuTensorHandle* dY, ev::Nullable<GpuTensorHandle> mask, Value KV, | |
| 547 | GpuTensorHandle* dX) { | ||
| 548 | 2 | const char* L = "maskedMeanPoolBackward"; | |
| 549 | 2 | const int32_t K = reqInt(KV, L, "K"); | |
| 550 | 2 | Tensor* mt = mask.ptr ? &mask.ptr->tensor : nullptr; | |
| 551 | 2 | needNonNegative(L, {K}); | |
| 552 | 2 | needMask(L, mt, K); | |
| 553 | 2 | BROTENSOR_API_TRY | |
| 554 | 2 | brotensor::masked_mean_pool_backward(dY->tensor, maskPtr(mt), K, dX->tensor); | |
| 555 | 2 | BROTENSOR_API_CATCH(L) | |
| 556 | 2 | } | |
| 557 | |||
| 558 | 2 | double nnSoftmaxXentFused(GpuTensorHandle* logits, GpuTensorHandle* target, | |
| 559 | ev::Nullable<GpuTensorHandle> mask, GpuTensorHandle* probs, | ||
| 560 | GpuTensorHandle* dLogits) { | ||
| 561 | 2 | const char* L = "softmaxXentFused"; | |
| 562 | 2 | Tensor* lt = &logits->tensor; | |
| 563 | 2 | Tensor* tt = &target->tensor; | |
| 564 | 2 | Tensor* mt = mask.ptr ? &mask.ptr->tensor : nullptr; | |
| 565 | 2 | needPair(L, "target", tt, lt); | |
| 566 | 2 | needMask(L, mt, lt->size()); | |
| 567 | 2 | BROTENSOR_API_TRY | |
| 568 | 2 | return brotensor::softmax_xent_fused(*lt, *tt, maskPtr(mt), probs->tensor, dLogits->tensor); | |
| 569 | 2 | BROTENSOR_API_CATCH(L) | |
| 570 | ✗ | return 0.0; | |
| 571 | 2 | } | |
| 572 | |||
| 573 | ✗ | void nnSoftmaxXentFusedBatched(GpuTensorHandle* logits_BL, GpuTensorHandle* target_BL, | |
| 574 | ev::Nullable<GpuTensorHandle> mask, GpuTensorHandle* headOffsets, | ||
| 575 | Value nHeadsV, GpuTensorHandle* probs_BL, GpuTensorHandle* dLogits_BL, | ||
| 576 | GpuTensorHandle* lossPerSample) { | ||
| 577 | ✗ | const char* L = "softmaxXentFusedBatched"; | |
| 578 | ✗ | const int32_t nHeads = reqInt(nHeadsV, L, "nHeads"); | |
| 579 | ✗ | Tensor* lt = &logits_BL->tensor; | |
| 580 | ✗ | Tensor* mt = mask.ptr ? &mask.ptr->tensor : nullptr; | |
| 581 | ✗ | Tensor* ht = &headOffsets->tensor; | |
| 582 | ✗ | needPair(L, "target_BL", &target_BL->tensor, lt); | |
| 583 | ✗ | needMask(L, mt, lt->size()); | |
| 584 | ✗ | needPositive(L, {nHeads}); | |
| 585 | ✗ | if (ht->dtype != Dtype::INT32) setError("softmaxXentFusedBatched: headOffsets must be INT32 storage"); | |
| 586 | ✗ | needElems(L, "headOffsets", ht, static_cast<int64_t>(nHeads) + 1); | |
| 587 | ✗ | BROTENSOR_API_TRY | |
| 588 | ✗ | auto host = ht->to(brotensor::Device::CPU); | |
| 589 | ✗ | const auto* off = static_cast<const int32_t*>(host.host_raw()); | |
| 590 | ✗ | for (int32_t h = 0; h <= nHeads; ++h) { | |
| 591 | ✗ | if (off[h] < 0 || off[h] > lt->cols || (h > 0 && off[h] < off[h - 1])) { | |
| 592 | ✗ | throw std::runtime_error("headOffsets must be non-decreasing within [0, logits.cols]"); | |
| 593 | } | ||
| 594 | ✗ | } | |
| 595 | ✗ | brotensor::softmax_xent_fused_batched(*lt, target_BL->tensor, maskPtr(mt), | |
| 596 | ✗ | static_cast<const int*>(ht->data), nHeads, | |
| 597 | ✗ | probs_BL->tensor, dLogits_BL->tensor, lossPerSample->tensor); | |
| 598 | ✗ | BROTENSOR_API_CATCH(L) | |
| 599 | ✗ | } | |
| 600 | |||
| 601 | 6 | void nnConcatRows(Value partsVal, GpuTensorHandle* out) { | |
| 602 | 6 | const char* L = "concatRows"; | |
| 603 | 6 | std::vector<Tensor*> parts; | |
| 604 | 6 | readTensorArrayVal(partsVal, parts, L); | |
| 605 | 4 | if (!parts.empty()) needOneDtype(L, parts, parts[0]); | |
| 606 | 2 | BROTENSOR_API_TRY | |
| 607 | 2 | brotensor::concat_rows(asConst(parts), out->tensor); | |
| 608 | 2 | BROTENSOR_API_CATCH(L) | |
| 609 | 6 | } | |
| 610 | |||
| 611 | 4 | void nnSplitRows(GpuTensorHandle* in, Value partsVal) { | |
| 612 | 4 | const char* L = "splitRows"; | |
| 613 | 4 | std::vector<Tensor*> parts; | |
| 614 | 4 | readTensorArrayVal(partsVal, parts, L); | |
| 615 | 4 | const Tensor* it = &in->tensor; | |
| 616 | 4 | needOneDtype(L, parts, it); | |
| 617 | 4 | int64_t total = 0; | |
| 618 | 12 | for (const Tensor* p : parts) total += p->size(); | |
| 619 | 4 | if (total > static_cast<int64_t>(it->size())) { | |
| 620 | 2 | setError("splitRows: the parts hold " + std::to_string(total) + " elements, in has " + std::to_string(it->size())); | |
| 621 | } | ||
| 622 | 2 | BROTENSOR_API_TRY | |
| 623 | 2 | brotensor::split_rows(*it, parts); | |
| 624 | 2 | BROTENSOR_API_CATCH(L) | |
| 625 | 6 | } | |
| 626 | |||
| 627 | 4 | void nnConcatBatchedRows(Value partsVal, GpuTensorHandle* out) { | |
| 628 | 4 | const char* L = "concatBatchedRows"; | |
| 629 | 4 | std::vector<Tensor*> parts; | |
| 630 | 4 | readTensorArrayVal(partsVal, parts, L); | |
| 631 | 4 | if (!parts.empty()) { | |
| 632 | 4 | needOneDtype(L, parts, parts[0]); | |
| 633 | 10 | for (const Tensor* p : parts) { | |
| 634 | 8 | if (p->rows != parts[0]->rows) { | |
| 635 | 2 | setError("concatBatchedRows: every part must have the same row count"); | |
| 636 | } | ||
| 637 | } | ||
| 638 | 2 | } | |
| 639 | 2 | BROTENSOR_API_TRY | |
| 640 | 2 | brotensor::concat_batched_rows(asConst(parts), out->tensor); | |
| 641 | 2 | BROTENSOR_API_CATCH(L) | |
| 642 | 4 | } | |
| 643 | |||
| 644 | 2 | void nnConcatNchwChannels(Value partsVal, int32_t N, int32_t H, int32_t W, | |
| 645 | Value cPerPartVal, GpuTensorHandle* out) { | ||
| 646 | 2 | const char* L = "concatNchwChannels"; | |
| 647 | 2 | const std::vector<int> channels = readChannelCounts(cPerPartVal, L); | |
| 648 | 2 | std::vector<Tensor*> parts; | |
| 649 | 2 | readTensorArrayVal(partsVal, parts, L); | |
| 650 | 2 | BROTENSOR_API_TRY | |
| 651 | 2 | brotensor::concat_nchw_channels(asConst(parts), N, H, W, channels, out->tensor); | |
| 652 | 2 | BROTENSOR_API_CATCH(L) | |
| 653 | 2 | } | |
| 654 | |||
| 655 | 2 | void nnConcatNchwChannelsBackward(GpuTensorHandle* dY, int32_t N, int32_t H, int32_t W, | |
| 656 | Value cPerPartVal, Value partsVal) { | ||
| 657 | 2 | const char* L = "concatNchwChannelsBackward"; | |
| 658 | 2 | const std::vector<int> channels = readChannelCounts(cPerPartVal, L); | |
| 659 | 2 | std::vector<Tensor*> parts; | |
| 660 | 2 | readTensorArrayVal(partsVal, parts, L); | |
| 661 | 2 | BROTENSOR_API_TRY | |
| 662 | 2 | brotensor::concat_nchw_channels_backward(dY->tensor, N, H, W, channels, parts); | |
| 663 | 2 | BROTENSOR_API_CATCH(L) | |
| 664 | 2 | } | |
| 665 | |||
| 666 | 2 | void nnRandUniform(Value keyV, Value counterV, GpuTensorHandle* Y) { | |
| 667 | 2 | const char* L = "randUniform"; | |
| 668 | 2 | uint64_t key = readSeedValue(keyV, 0, L); | |
| 669 | 2 | uint64_t counter = readSeedValue(counterV, 0, L); | |
| 670 | 2 | needFp32Out(L, &Y->tensor); | |
| 671 | 2 | BROTENSOR_API_TRY | |
| 672 | 2 | brotensor::rand_uniform(key, counter, Y->tensor); | |
| 673 | 2 | BROTENSOR_API_CATCH(L) | |
| 674 | 2 | } | |
| 675 | |||
| 676 | 12 | void nnRandn(Value keyV, Value counterV, GpuTensorHandle* Y) { | |
| 677 | 12 | const char* L = "randn"; | |
| 678 | 12 | uint64_t key = readSeedValue(keyV, 0, L); | |
| 679 | 12 | uint64_t counter = readSeedValue(counterV, 0, L); | |
| 680 | 12 | needFp32Out(L, &Y->tensor); | |
| 681 | 12 | BROTENSOR_API_TRY | |
| 682 | 12 | brotensor::randn(key, counter, Y->tensor); | |
| 683 | 12 | BROTENSOR_API_CATCH(L) | |
| 684 | 12 | } | |
| 685 | |||
| 686 | 4 | void nnRandBernoulli(double p, Value keyV, Value counterV, GpuTensorHandle* Y) { | |
| 687 | 4 | const char* L = "randBernoulli"; | |
| 688 | 4 | uint64_t key = readSeedValue(keyV, 0, L); | |
| 689 | 4 | uint64_t counter = readSeedValue(counterV, 0, L); | |
| 690 | 4 | needFp32Out(L, &Y->tensor); | |
| 691 | 4 | BROTENSOR_API_TRY | |
| 692 | 4 | brotensor::rand_bernoulli(static_cast<float>(p), key, counter, Y->tensor); | |
| 693 | 4 | BROTENSOR_API_CATCH(L) | |
| 694 | 4 | } | |
| 695 | |||
| 696 | 2 | void nnRandnTruncated(double lo, double hi, Value keyV, Value counterV, GpuTensorHandle* Y) { | |
| 697 | 2 | const char* L = "randnTruncated"; | |
| 698 | 2 | uint64_t key = readSeedValue(keyV, 0, L); | |
| 699 | 2 | uint64_t counter = readSeedValue(counterV, 0, L); | |
| 700 | 2 | needFp32Out(L, &Y->tensor); | |
| 701 | 2 | BROTENSOR_API_TRY | |
| 702 | 2 | brotensor::randn_truncated(static_cast<float>(lo), static_cast<float>(hi), key, counter, Y->tensor); | |
| 703 | 2 | BROTENSOR_API_CATCH(L) | |
| 704 | 2 | } | |
| 705 | |||
| 706 | ✗ | double nnXavierInit(GpuTensorHandle* W, Value stateV) { | |
| 707 | ✗ | uint64_t state = readSeedValue(stateV, 0, "xavierInit"); | |
| 708 | ✗ | BROTENSOR_API_TRY | |
| 709 | ✗ | brotensor::xavier_init(W->tensor, state); | |
| 710 | ✗ | BROTENSOR_API_CATCH("xavierInit") | |
| 711 | ✗ | return static_cast<double>(state); | |
| 712 | ✗ | } | |
| 713 | |||
| 714 | } // namespace | ||
| 715 | |||
| 716 | 2 | void installTensorNn(bronze::Value ns) { | |
| 717 | 4 | ev::bindNamespace(ns, "bro.tensor") | |
| 718 | 2 | .fn<&nnLayernormForward>("layernormForward") | |
| 719 | 2 | .requiredFn<&nnLayernormBackward>("layernormBackward") | |
| 720 | 2 | .fn<&nnLayernormForwardInferenceBatched>("layernormForwardInferenceBatched") | |
| 721 | 2 | .fn<&nnLayernormForwardInferenceBatchedFp16>("layernormForwardInferenceBatchedFp16") | |
| 722 | 2 | .requiredFn<&nnRmsNormForward>("rmsNormForward") | |
| 723 | 2 | .requiredFn<&nnRmsNormBackward>("rmsNormBackward") | |
| 724 | 2 | .requiredFn<&nnGroupNormForward>("groupNormForward") | |
| 725 | 2 | .requiredFn<&nnGroupNormBackward>("groupNormBackward") | |
| 726 | 2 | .requiredFn<&nnRopeForward>("ropeForward") | |
| 727 | 2 | .requiredFn<&nnRopeBackward>("ropeBackward") | |
| 728 | 2 | .requiredFn<&nnRopeApply>("ropeApply") | |
| 729 | 2 | .requiredFn<&nnRopeApplyBackward>("ropeApplyBackward") | |
| 730 | 2 | .requiredFn<&nnModulate>("modulate") | |
| 731 | 2 | .requiredFn<&nnBroadcastMul>("broadcastMul") | |
| 732 | 2 | .requiredFn<&nnAttentionTokenMoments>("attentionTokenMoments") | |
| 733 | 2 | .requiredFn<&nnBuildSlotMask>("buildSlotMask") | |
| 734 | 2 | .requiredFn<&nnBuildCausalMaskRow>("buildCausalMaskRow") | |
| 735 | 2 | .fn<&nnFlashAttentionDecode>("flashAttentionDecode") | |
| 736 | 2 | .fn<&nnFlashAttentionDecodeMasked>("flashAttentionDecodeMasked") | |
| 737 | 2 | .requiredFn<&nnKvCacheAppend>("kvCacheAppend") | |
| 738 | 2 | .requiredFn<&nnEmbeddingLookupForward>("embeddingLookupForward") | |
| 739 | 2 | .requiredFn<&nnEmbeddingLookupBackward>("embeddingLookupBackward") | |
| 740 | 2 | .requiredFn<&nnSgdStep>("sgdStep") | |
| 741 | 2 | .requiredFn<&nnAdamStep>("adamStep") | |
| 742 | 2 | .fn<&nnCast>("cast") | |
| 743 | 2 | .fn<&nnMaskedMeanPoolForward>("maskedMeanPoolForward") | |
| 744 | 2 | .fn<&nnMaskedMeanPoolBackward>("maskedMeanPoolBackward") | |
| 745 | 2 | .fn<&nnSoftmaxXentFused>("softmaxXentFused") | |
| 746 | 2 | .fn<&nnSoftmaxXentFusedBatched>("softmaxXentFusedBatched") | |
| 747 | 2 | .requiredFn<&nnConcatRows>("concatRows") | |
| 748 | 2 | .requiredFn<&nnSplitRows>("splitRows") | |
| 749 | 2 | .requiredFn<&nnConcatBatchedRows>("concatBatchedRows") | |
| 750 | 2 | .requiredFn<&nnConcatNchwChannels>("concatNchwChannels") | |
| 751 | 2 | .requiredFn<&nnConcatNchwChannelsBackward>("concatNchwChannelsBackward") | |
| 752 | 2 | .requiredFn<&nnRandUniform>("randUniform") | |
| 753 | 2 | .requiredFn<&nnRandn>("randn") | |
| 754 | 2 | .requiredFn<&nnRandBernoulli>("randBernoulli") | |
| 755 | 2 | .requiredFn<&nnRandnTruncated>("randnTruncated") | |
| 756 | 2 | .requiredFn<&nnXavierInit>("xavierInit"); | |
| 757 | 2 | } | |
| 758 | |||
| 759 | } // namespace brotensor::api | ||
| 760 |