src/api/native_tensor_misc.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | // native_tensor_misc.cpp — gated-deltanet L2 norm, remaining losses, | ||
| 2 | // diffusion sampler steps, timestep embedding, kernel cache, warmup & bundles. | ||
| 3 | |||
| 4 | #include "api_internal.h" | ||
| 5 | #include <brotensor/kernel_cache.h> | ||
| 6 | |||
| 7 | #include <cmath> | ||
| 8 | #include <cstdint> | ||
| 9 | #include <string> | ||
| 10 | |||
| 11 | namespace brotensor::api { | ||
| 12 | |||
| 13 | namespace { | ||
| 14 | |||
| 15 | namespace ev = bronze::embed; | ||
| 16 | using brotensor::Tensor; | ||
| 17 | |||
| 18 | 196 | inline bronze::Value argAt(std::span<const bronze::Value> a, size_t i) { | |
| 19 | 196 | return i < a.size() ? a[i] : ev::undefined(); | |
| 20 | } | ||
| 21 | |||
| 22 | 24 | inline int32_t toInt32Js(double d) { | |
| 23 | 24 | if (!std::isfinite(d) || d == 0.0) return 0; | |
| 24 | 22 | double t = std::trunc(d); | |
| 25 | 22 | double rem = std::fmod(t, 4294967296.0); | |
| 26 | 22 | if (rem < 0.0) rem += 4294967296.0; | |
| 27 | 22 | return static_cast<int32_t>(static_cast<uint32_t>(rem)); | |
| 28 | 24 | } | |
| 29 | |||
| 30 | 24 | inline int32_t intArg(bronze::Value v, int32_t def) { | |
| 31 | 24 | if (ev::isUndefined(v) || ev::isNull(v)) return def; | |
| 32 | 24 | return toInt32Js(ev::toDouble(v)); | |
| 33 | 24 | } | |
| 34 | |||
| 35 | 46 | inline double numArg(bronze::Value v, double def) { | |
| 36 | 46 | if (ev::isUndefined(v) || ev::isNull(v)) return def; | |
| 37 | 44 | return ev::toDouble(v); | |
| 38 | 46 | } | |
| 39 | |||
| 40 | 8 | inline bool boolArg(bronze::Value v, bool def) { | |
| 41 | 8 | if (ev::isUndefined(v) || ev::isNull(v)) return def; | |
| 42 | 8 | return ev::toBool(v); | |
| 43 | 8 | } | |
| 44 | |||
| 45 | // X is (L, numHeads*headDim), both positive. | ||
| 46 | 6 | inline void needHeadCols(const char* L, const Tensor* x, int32_t headDim, int32_t numHeads) { | |
| 47 | 6 | needPositive(L, {headDim, numHeads}); | |
| 48 | 6 | if (static_cast<int64_t>(x->cols) != static_cast<int64_t>(numHeads) * headDim) { | |
| 49 | 2 | setError(std::string(L) + ": X must have numHeads*headDim columns"); | |
| 50 | } | ||
| 51 | 6 | } | |
| 52 | |||
| 53 | 18 | inline ev::TypedArrayInfo requireF32Array(bronze::Value v, const char* L, const char* name) { | |
| 54 | 18 | ev::TypedArrayInfo info = ev::typedArrayInfo(v); | |
| 55 | 18 | if (!info || info.elementKind != ev::elements::Float32) { | |
| 56 | 2 | ev::throwTypeError(std::string(L) + ": " + name + " must be a Float32Array"); | |
| 57 | } | ||
| 58 | 16 | return info; | |
| 59 | 2 | } | |
| 60 | |||
| 61 | 4 | inline ev::TypedArrayInfo optionalF32Array(bronze::Value v, const char* L, const char* name) { | |
| 62 | 4 | if (ev::isUndefined(v) || ev::isNull(v)) return ev::TypedArrayInfo{}; | |
| 63 | 2 | ev::TypedArrayInfo info = ev::typedArrayInfo(v); | |
| 64 | 2 | if (!info || info.elementKind != ev::elements::Float32) { | |
| 65 | ✗ | ev::throwTypeError(std::string(L) + ": " + name + " must be null or a Float32Array"); | |
| 66 | } | ||
| 67 | 2 | return info; | |
| 68 | 4 | } | |
| 69 | |||
| 70 | } // namespace | ||
| 71 | |||
| 72 | 2 | void installTensorMisc(bronze::Value ns) { | |
| 73 | 2 | ev::ObjectBuilder b(ns); | |
| 74 | |||
| 75 | // ---- L2 norm ----------------------------------------------------------- | ||
| 76 | 4 | b.def("l2NormForward", 5, [](bronze::Value, std::span<const bronze::Value> a) -> bronze::Value { | |
| 77 | 2 | constexpr const char* L = "l2NormForward"; | |
| 78 | 2 | Tensor* X = requireTensor(argAt(a, 0), L, "X"); | |
| 79 | 2 | const int32_t headDim = intArg(argAt(a, 1), 0); | |
| 80 | 2 | const int32_t numHeads = intArg(argAt(a, 2), 1); | |
| 81 | 2 | const double eps = numArg(argAt(a, 3), 0.000001); | |
| 82 | 2 | Tensor* Y = requireTensor(argAt(a, 4), L, "Y"); | |
| 83 | 2 | needHeadCols(L, X, headDim, numHeads); | |
| 84 | 2 | BROTENSOR_API_TRY | |
| 85 | 2 | brotensor::l2_norm_forward(*X, headDim, numHeads, static_cast<float>(eps), *Y); | |
| 86 | 2 | BROTENSOR_API_CATCH(L) | |
| 87 | 2 | return ev::undefined(); | |
| 88 | ✗ | }); | |
| 89 | |||
| 90 | 4 | b.def("l2NormBackward", 6, [](bronze::Value, std::span<const bronze::Value> a) -> bronze::Value { | |
| 91 | 2 | constexpr const char* L = "l2NormBackward"; | |
| 92 | 2 | Tensor* X = requireTensor(argAt(a, 0), L, "X"); | |
| 93 | 2 | const int32_t headDim = intArg(argAt(a, 1), 0); | |
| 94 | 2 | const int32_t numHeads = intArg(argAt(a, 2), 1); | |
| 95 | 2 | const double eps = numArg(argAt(a, 3), 0.000001); | |
| 96 | 2 | Tensor* dY = requireTensor(argAt(a, 4), L, "dY"); | |
| 97 | 2 | Tensor* dX = requireTensor(argAt(a, 5), L, "dX"); | |
| 98 | 2 | needHeadCols(L, X, headDim, numHeads); | |
| 99 | 2 | needPair(L, "dY", dY, X); | |
| 100 | 2 | BROTENSOR_API_TRY | |
| 101 | 2 | brotensor::l2_norm_backward(*X, headDim, numHeads, static_cast<float>(eps), *dY, *dX); | |
| 102 | 2 | BROTENSOR_API_CATCH(L) | |
| 103 | 2 | return ev::undefined(); | |
| 104 | ✗ | }); | |
| 105 | |||
| 106 | // ---- losses ------------------------------------------------------------ | ||
| 107 | 8 | b.def("bceWithLogitsFusedBatched", 7, [](bronze::Value, std::span<const bronze::Value> a) -> bronze::Value { | |
| 108 | 6 | constexpr const char* L = "bceWithLogitsFusedBatched"; | |
| 109 | 6 | Tensor* logits = requireTensor(argAt(a, 0), L, "logits"); | |
| 110 | 6 | Tensor* target = requireTensor(argAt(a, 1), L, "target"); | |
| 111 | 6 | Tensor* mask = optionalTensor(argAt(a, 2), L, "mask"); | |
| 112 | 6 | const double posWeight = numArg(argAt(a, 3), 1.0); | |
| 113 | 6 | Tensor* probs = requireTensor(argAt(a, 4), L, "probs"); | |
| 114 | 6 | Tensor* dLogits = requireTensor(argAt(a, 5), L, "dLogits"); | |
| 115 | 6 | Tensor* lossPerSample = requireTensor(argAt(a, 6), L, "lossPerSample"); | |
| 116 | 6 | needPair(L, "target_BL", target, logits); | |
| 117 | 6 | needMask(L, mask, logits->size()); | |
| 118 | 6 | BROTENSOR_API_TRY | |
| 119 | 6 | brotensor::bce_with_logits_fused_batched(*logits, *target, maskPtr(mask), | |
| 120 | 6 | static_cast<float>(posWeight), | |
| 121 | 6 | *probs, *dLogits, *lossPerSample); | |
| 122 | 6 | BROTENSOR_API_CATCH(L) | |
| 123 | 6 | return ev::undefined(); | |
| 124 | ✗ | }); | |
| 125 | |||
| 126 | 6 | b.def("softmaxXentSegment", 6, [](bronze::Value, std::span<const bronze::Value> a) -> bronze::Value { | |
| 127 | 4 | constexpr const char* L = "softmaxXentSegment(logits,target,probs,dLogits,n,mask|null)"; | |
| 128 | 4 | const ev::TypedArrayInfo logits = requireF32Array(argAt(a, 0), L, "logits"); | |
| 129 | 4 | const ev::TypedArrayInfo target = requireF32Array(argAt(a, 1), L, "target"); | |
| 130 | 4 | const ev::TypedArrayInfo probs = requireF32Array(argAt(a, 2), L, "probs"); | |
| 131 | 4 | const ev::TypedArrayInfo dLogits = requireF32Array(argAt(a, 3), L, "dLogits"); | |
| 132 | 4 | const int32_t n = intArg(argAt(a, 4), 0); | |
| 133 | 4 | const ev::TypedArrayInfo mask = optionalF32Array(argAt(a, 5), L, "mask"); | |
| 134 | |||
| 135 | 4 | if (n <= 0) { | |
| 136 | ✗ | setError("softmaxXentSegment: n must be positive"); | |
| 137 | } | ||
| 138 | 4 | const uint32_t un = static_cast<uint32_t>(n); | |
| 139 | 8 | if (logits.elementCount < un || target.elementCount < un || | |
| 140 | 4 | probs.elementCount < un || dLogits.elementCount < un) { | |
| 141 | ✗ | setError("softmaxXentSegment: a buffer holds fewer than n=" + std::to_string(n) + " elements"); | |
| 142 | } | ||
| 143 | 4 | const float* maskPtrVal = (mask.data && mask.elementCount > 0) | |
| 144 | 2 | ? reinterpret_cast<const float*>(mask.data) | |
| 145 | : nullptr; | ||
| 146 | 4 | if (maskPtrVal && mask.elementCount < un) { | |
| 147 | ✗ | setError("softmaxXentSegment: mask holds fewer than n=" + std::to_string(n) + " elements"); | |
| 148 | } | ||
| 149 | |||
| 150 | // No allocating bronze::embed calls while raw typed-array pointers are live. | ||
| 151 | 4 | double loss = 0.0; | |
| 152 | 4 | BROTENSOR_API_TRY | |
| 153 | 4 | loss = brotensor::softmax_xent_segment( | |
| 154 | 4 | reinterpret_cast<const float*>(logits.data), | |
| 155 | 4 | reinterpret_cast<const float*>(target.data), | |
| 156 | 4 | reinterpret_cast<float*>(probs.data), | |
| 157 | 4 | reinterpret_cast<float*>(dLogits.data), | |
| 158 | 4 | n, maskPtrVal); | |
| 159 | 4 | BROTENSOR_API_CATCH("softmaxXentSegment") | |
| 160 | 4 | return ev::fromDouble(loss); | |
| 161 | ✗ | }); | |
| 162 | |||
| 163 | 6 | b.def("mseScalar", 2, [](bronze::Value, std::span<const bronze::Value> a) -> bronze::Value { | |
| 164 | 4 | const double pred = numArg(argAt(a, 0), 0.0); | |
| 165 | 4 | const double target = numArg(argAt(a, 1), 0.0); | |
| 166 | 4 | float dPred = 0.0f; | |
| 167 | 4 | float loss = 0.0f; | |
| 168 | 4 | BROTENSOR_API_TRY | |
| 169 | 4 | loss = brotensor::mse_scalar(static_cast<float>(pred), static_cast<float>(target), dPred); | |
| 170 | 4 | BROTENSOR_API_CATCH("mseScalar") | |
| 171 | 4 | ev::ArrayBuilder out(2); | |
| 172 | 4 | out.set(0, static_cast<double>(loss)); | |
| 173 | 4 | out.set(1, static_cast<double>(dPred)); | |
| 174 | 4 | return out.build(); | |
| 175 | 4 | }); | |
| 176 | |||
| 177 | // ---- diffusion sampler steps + timestep embedding ---------------------- | ||
| 178 | 4 | b.def("ddimStep", 6, [](bronze::Value, std::span<const bronze::Value> a) -> bronze::Value { | |
| 179 | 2 | constexpr const char* L = "ddimStep"; | |
| 180 | 2 | Tensor* x_t = requireTensor(argAt(a, 0), L, "x_t"); | |
| 181 | 2 | Tensor* eps_pred = requireTensor(argAt(a, 1), L, "eps_pred"); | |
| 182 | 2 | const double alphaT = numArg(argAt(a, 2), 0.0); | |
| 183 | 2 | const double alphaPrev = numArg(argAt(a, 3), 0.0); | |
| 184 | 2 | const double sigmaT = numArg(argAt(a, 4), 0.0); | |
| 185 | 2 | Tensor* x_prev = requireTensor(argAt(a, 5), L, "x_prev"); | |
| 186 | 2 | needPair(L, "eps_pred", eps_pred, x_t); | |
| 187 | 2 | BROTENSOR_API_TRY | |
| 188 | 4 | brotensor::ddim_step(*x_t, *eps_pred, static_cast<float>(alphaT), | |
| 189 | 2 | static_cast<float>(alphaPrev), static_cast<float>(sigmaT), *x_prev); | |
| 190 | 2 | BROTENSOR_API_CATCH(L) | |
| 191 | 2 | return ev::undefined(); | |
| 192 | ✗ | }); | |
| 193 | |||
| 194 | 4 | b.def("eulerStep", 5, [](bronze::Value, std::span<const bronze::Value> a) -> bronze::Value { | |
| 195 | 2 | constexpr const char* L = "eulerStep"; | |
| 196 | 2 | Tensor* x_t = requireTensor(argAt(a, 0), L, "x_t"); | |
| 197 | 2 | Tensor* eps_pred = requireTensor(argAt(a, 1), L, "eps_pred"); | |
| 198 | 2 | const double sigmaT = numArg(argAt(a, 2), 0.0); | |
| 199 | 2 | const double sigmaPrev = numArg(argAt(a, 3), 0.0); | |
| 200 | 2 | Tensor* x_prev = requireTensor(argAt(a, 4), L, "x_prev"); | |
| 201 | 2 | needPair(L, "eps_pred", eps_pred, x_t); | |
| 202 | 2 | BROTENSOR_API_TRY | |
| 203 | 4 | brotensor::euler_step(*x_t, *eps_pred, static_cast<float>(sigmaT), | |
| 204 | 2 | static_cast<float>(sigmaPrev), *x_prev); | |
| 205 | 2 | BROTENSOR_API_CATCH(L) | |
| 206 | 2 | return ev::undefined(); | |
| 207 | ✗ | }); | |
| 208 | |||
| 209 | 4 | b.def("dpmpp2mStep", 9, [](bronze::Value, std::span<const bronze::Value> a) -> bronze::Value { | |
| 210 | 2 | constexpr const char* L = "dpmpp2mStep"; | |
| 211 | 2 | Tensor* x_t = requireTensor(argAt(a, 0), L, "x_t"); | |
| 212 | 2 | Tensor* eps_pred = requireTensor(argAt(a, 1), L, "eps_pred"); | |
| 213 | 2 | Tensor* x0_prev = requireTensor(argAt(a, 2), L, "x0_prev"); | |
| 214 | 2 | const double sigmaT = numArg(argAt(a, 3), 0.0); | |
| 215 | 2 | const double c_xt = numArg(argAt(a, 4), 0.0); | |
| 216 | 2 | const double c_x0t = numArg(argAt(a, 5), 0.0); | |
| 217 | 2 | const double c_x0prev = numArg(argAt(a, 6), 0.0); | |
| 218 | 2 | Tensor* x_prev = requireTensor(argAt(a, 7), L, "x_prev"); | |
| 219 | 2 | Tensor* x0_out = requireTensor(argAt(a, 8), L, "x0_out"); | |
| 220 | 2 | needPair(L, "eps_pred", eps_pred, x_t); | |
| 221 | 2 | needPair(L, "x0_prev", x0_prev, x_t); | |
| 222 | 2 | BROTENSOR_API_TRY | |
| 223 | 4 | brotensor::dpmpp_2m_step(*x_t, *eps_pred, *x0_prev, static_cast<float>(sigmaT), | |
| 224 | 2 | static_cast<float>(c_xt), static_cast<float>(c_x0t), | |
| 225 | 2 | static_cast<float>(c_x0prev), *x_prev, *x0_out); | |
| 226 | 2 | BROTENSOR_API_CATCH(L) | |
| 227 | 2 | return ev::undefined(); | |
| 228 | ✗ | }); | |
| 229 | |||
| 230 | 10 | b.def("timestepEmbedding", 4, [](bronze::Value, std::span<const bronze::Value> a) -> bronze::Value { | |
| 231 | 8 | constexpr const char* L = "timestepEmbedding"; | |
| 232 | 8 | Tensor* timesteps = requireTensor(argAt(a, 0), L, "timesteps"); | |
| 233 | 8 | const int32_t dim = intArg(argAt(a, 1), 0); | |
| 234 | 8 | const double maxPeriod = numArg(argAt(a, 2), 10000.0); | |
| 235 | 8 | Tensor* Y = requireTensor(argAt(a, 3), L, "Y"); | |
| 236 | 8 | needNonNegative(L, {dim}); | |
| 237 | 8 | BROTENSOR_API_TRY | |
| 238 | 8 | brotensor::timestep_embedding(*timesteps, dim, static_cast<float>(maxPeriod), *Y); | |
| 239 | 10 | BROTENSOR_API_CATCH(L) | |
| 240 | 6 | return ev::undefined(); | |
| 241 | 4 | }); | |
| 242 | |||
| 243 | // ---- kernel disk cache, warmup & bundles ------------------------------- | ||
| 244 | 6 | b.def("cacheStats", 0, [](bronze::Value, std::span<const bronze::Value>) -> bronze::Value { | |
| 245 | 4 | std::string dir; | |
| 246 | 4 | brotensor::KernelCacheStats s{}; | |
| 247 | 4 | BROTENSOR_API_TRY | |
| 248 | 4 | dir = brotensor::kernel_cache_dir(); | |
| 249 | 4 | s = brotensor::kernel_cache_stats(); | |
| 250 | 4 | BROTENSOR_API_CATCH("cacheStats") | |
| 251 | ev::ObjectBuilder obj; | ||
| 252 | obj.set("dir", dir); | ||
| 253 | obj.set("hits", static_cast<double>(s.hits)); | ||
| 254 | obj.set("misses", static_cast<double>(s.misses)); | ||
| 255 | obj.set("writes", static_cast<double>(s.writes)); | ||
| 256 | obj.set("corruptions", static_cast<double>(s.corruptions)); | ||
| 257 | obj.set("entries", static_cast<double>(s.entries)); | ||
| 258 | return obj.build(); | ||
| 259 | ✗ | }); | |
| 260 | |||
| 261 | 8 | b.def("setAutotune", 1, [](bronze::Value, std::span<const bronze::Value> a) -> bronze::Value { | |
| 262 | 6 | brotensor::set_autotune_enabled(boolArg(argAt(a, 0), false)); | |
| 263 | 6 | return ev::undefined(); | |
| 264 | }); | ||
| 265 | |||
| 266 | 8 | b.def("autotuneEnabled", 0, [](bronze::Value, std::span<const bronze::Value>) -> bronze::Value { | |
| 267 | 6 | return ev::fromBool(brotensor::autotune_enabled()); | |
| 268 | }); | ||
| 269 | |||
| 270 | 4 | b.def("warmupKernels", 2, [](bronze::Value, std::span<const bronze::Value> a) -> bronze::Value { | |
| 271 | 2 | bronze::Value pVal = argAt(a, 0); | |
| 272 | 2 | std::string profile = (ev::isUndefined(pVal) || ev::isNull(pVal)) | |
| 273 | ✗ | ? std::string("default") | |
| 274 | 2 | : ev::toUtf8(pVal); | |
| 275 | 2 | const bool autotune = boolArg(argAt(a, 1), false); | |
| 276 | 2 | brotensor::WarmupStats w{}; | |
| 277 | 2 | BROTENSOR_API_TRY | |
| 278 | 2 | brotensor::WarmupOptions opts; | |
| 279 | 2 | if (!profile.empty()) opts.profile = profile; | |
| 280 | 2 | opts.autotune = autotune; | |
| 281 | 2 | w = brotensor::warmup_kernels(brotensor::default_device(), opts); | |
| 282 | 2 | BROTENSOR_API_CATCH("warmupKernels") | |
| 283 | ev::ObjectBuilder obj; | ||
| 284 | obj.set("kernelsCompiled", static_cast<double>(w.kernels_compiled)); | ||
| 285 | obj.set("autotuneEntries", static_cast<double>(w.autotune_entries)); | ||
| 286 | obj.set("elapsedMs", w.elapsed_ms); | ||
| 287 | return obj.build(); | ||
| 288 | ✗ | }); | |
| 289 | |||
| 290 | 4 | b.def("exportKernelBundle", 1, [](bronze::Value, std::span<const bronze::Value> a) -> bronze::Value { | |
| 291 | 2 | bronze::Value pVal = argAt(a, 0); | |
| 292 | 2 | if (!ev::isString(pVal)) { | |
| 293 | ✗ | ev::throwTypeError("exportKernelBundle(path): expected string path"); | |
| 294 | } | ||
| 295 | 2 | std::string path = ev::toUtf8(pVal); | |
| 296 | 2 | std::string resolved = gatedPath(path.c_str(), /*write=*/true); | |
| 297 | 2 | bool ok = false; | |
| 298 | 2 | std::string err; | |
| 299 | 2 | BROTENSOR_API_TRY | |
| 300 | 2 | ok = brotensor::export_kernel_bundle(resolved, brotensor::default_device(), &err); | |
| 301 | 2 | BROTENSOR_API_CATCH("exportKernelBundle") | |
| 302 | 2 | if (!ok) { | |
| 303 | ✗ | setError("exportKernelBundle: " + (err.empty() ? "failed" : err)); | |
| 304 | } | ||
| 305 | 2 | return ev::undefined(); | |
| 306 | 2 | }); | |
| 307 | |||
| 308 | 4 | b.def("importKernelBundle", 1, [](bronze::Value, std::span<const bronze::Value> a) -> bronze::Value { | |
| 309 | 2 | bronze::Value pVal = argAt(a, 0); | |
| 310 | 2 | if (!ev::isString(pVal)) { | |
| 311 | ✗ | ev::throwTypeError("importKernelBundle(path): expected string path"); | |
| 312 | } | ||
| 313 | 2 | std::string path = ev::toUtf8(pVal); | |
| 314 | 2 | std::string resolved = gatedPath(path.c_str(), /*write=*/false); | |
| 315 | 2 | brotensor::BundleImportReport rep{}; | |
| 316 | bool ok = false; | ||
| 317 | std::string err; | ||
| 318 | 2 | BROTENSOR_API_TRY | |
| 319 | 2 | ok = brotensor::import_kernel_bundle(resolved, &rep, &err); | |
| 320 | 2 | BROTENSOR_API_CATCH("importKernelBundle") | |
| 321 | 2 | if (!ok) { | |
| 322 | ✗ | setError("importKernelBundle: " + (err.empty() ? "failed" : err)); | |
| 323 | } | ||
| 324 | ev::ObjectBuilder obj; | ||
| 325 | obj.set("entriesImported", static_cast<double>(rep.entries_imported)); | ||
| 326 | obj.set("entriesSkipped", static_cast<double>(rep.entries_skipped)); | ||
| 327 | obj.set("bytes", static_cast<double>(rep.bytes)); | ||
| 328 | return obj.build(); | ||
| 329 | ✗ | }); | |
| 330 | 2 | } | |
| 331 | |||
| 332 | } // namespace brotensor::api | ||
| 333 |