brotensor/
Coverage:
low: ≥ 0%
medium: ≥ 75.0%
high: ≥ 90.0%
Lines:
135 / 143
94.4%
Branches:
44 / 76
57.9%
Functions:
12 / 13
92.3%

src/cpu/noise.cpp
Line Branch Exec Source
1 // ─── CPU counter-based noise generation ─────────────────────────────────────
2 //
3 // Philox 4x32-10 stream (PyTorch / JAX compatible) implementing four host-side
4 // FP32 noise ops:
5 // randn — N(0, 1) via Box-Muller
6 // rand_uniform — U[0, 1)
7 // rand_bernoulli — 0/1 mask at probability p
8 // randn_truncated — rejection-sampled normal in [lo, hi]
9 //
10 // All four require Y FP32 and pre-sized; the op fills rows*cols elements in
11 // row-major linear order. Element i draws from substream (counter + i); see
12 // ops.h for the full ABI contract.
13 //
14 // The Philox construction here is byte-identical to src/cpu/sample_logits.cpp
15 // and the CUDA / Metal noise implementations, so a given (key, counter) yields
16 // the same draws on every backend.
17
18 #include <brotensor/tensor.h>
19
20 #include <cmath>
21 #include <cstddef>
22 #include <cstdint>
23 #include <stdexcept>
24 #include <string>
25
26 namespace brotensor::detail::cpu {
27
28 namespace {
29
30 ✗ [[noreturn]] void fail(const char* op, const std::string& reason) {
31
0/14
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✗ Branch 5 not taken.
✗ Branch 6 not taken.
✗ Branch 7 not taken.
✗ Branch 8 not taken.
✗ Branch 9 not taken.
✗ Branch 10 not taken.
✗ Branch 11 not taken.
✗ Branch 12 not taken.
✗ Branch 13 not taken.
✗ throw std::runtime_error(std::string("brotensor: ") + op + ": " + reason);
32 ✗ }
33
34 // ── Philox 4x32-10 ──────────────────────────────────────────────────────────
35 // Same construction as sample_logits.cpp; duplicated rather than shared so the
36 // translation units stay independent.
37
38 29662300 inline void mulhilo32(uint32_t a, uint32_t b, uint32_t& hi, uint32_t& lo) {
39 29662300 const uint64_t p = static_cast<uint64_t>(a) * static_cast<uint64_t>(b);
40 29662300 hi = static_cast<uint32_t>(p >> 32);
41 29662300 lo = static_cast<uint32_t>(p);
42 29662300 }
43
44 14831150 inline void philox_round(uint32_t ctr[4], const uint32_t key[2]) {
45 uint32_t hi0, lo0, hi1, lo1;
46 14831150 mulhilo32(0xD2511F53u, ctr[0], hi0, lo0);
47 14831150 mulhilo32(0xCD9E8D57u, ctr[2], hi1, lo1);
48 14831150 const uint32_t n0 = hi1 ^ ctr[1] ^ key[0];
49 14831150 const uint32_t n1 = lo1;
50 14831150 const uint32_t n2 = hi0 ^ ctr[3] ^ key[1];
51 14831150 const uint32_t n3 = lo0;
52 14831150 ctr[0] = n0; ctr[1] = n1; ctr[2] = n2; ctr[3] = n3;
53 14831150 }
54
55 // Run all ten rounds for substream `substream` under `key64`. Output is the
56 // four mixed counter words ctr[0..3] (each a uniformly distributed uint32).
57 1483115 inline void philox4x32(uint64_t key64, uint64_t substream, uint32_t out[4]) {
58 2966230 uint32_t key[2] = {
59 1483115 static_cast<uint32_t>(key64 & 0xFFFFFFFFull),
60 1483115 static_cast<uint32_t>(key64 >> 32),
61 };
62 2966230 uint32_t ctr[4] = {
63 1483115 static_cast<uint32_t>(substream & 0xFFFFFFFFull),
64 1483115 static_cast<uint32_t>(substream >> 32),
65 0u, 0u,
66 };
67
2/2
✓ Branch 0 taken 14831150 times.
✓ Branch 1 taken 1483115 times.
16314265 for (int r = 0; r < 10; ++r) {
68 14831150 philox_round(ctr, key);
69
2/2
✓ Branch 0 taken 1483115 times.
✓ Branch 1 taken 13348035 times.
14831150 if (r < 9) {
70 13348035 key[0] += 0x9E3779B9u;
71 13348035 key[1] += 0xBB67AE85u;
72 13348035 }
73 14831150 }
74 1483115 out[0] = ctr[0]; out[1] = ctr[1]; out[2] = ctr[2]; out[3] = ctr[3];
75 1483115 }
76
77 // Top 24 bits / 2^24 -> uniform in [0, 1). Matches xavier_init / sample_logits.
78 2715974 inline float u01_from(uint32_t w) {
79 2715974 return static_cast<float>(w >> 8) * (1.0f / 16777216.0f);
80 }
81
82 // One uniform draw for substream `substream` (use ctr[0] only).
83 250256 inline float philox_uniform(uint64_t key64, uint64_t substream) {
84 uint32_t ctr[4];
85 250256 philox4x32(key64, substream, ctr);
86 250256 return u01_from(ctr[0]);
87 }
88
89 // One standard-normal draw via Box-Muller on (ctr[0], ctr[1]). We use
90 // 1 - u1 so log() stays finite for u1 == 0.
91 1232859 inline float philox_normal(uint64_t key64, uint64_t substream) {
92 uint32_t ctr[4];
93 1232859 philox4x32(key64, substream, ctr);
94 1232859 const float u1 = 1.0f - u01_from(ctr[0]); // (0, 1]
95 1232859 const float u2 = u01_from(ctr[1]); // [0, 1)
96 1232859 constexpr double kTwoPi = 2.0 * 3.14159265358979323846;
97 1232859 const float radius = std::sqrt(-2.0f * std::log(u1));
98 1232859 const float theta =
99 1232859 static_cast<float>(kTwoPi * static_cast<double>(u2));
100 1232859 return radius * std::cos(theta);
101 }
102
103 // Common entry validation for the four ops.
104 16 inline std::size_t check_y(const char* op, const ::brotensor::Tensor& Y) {
105
1/2
✓ Branch 0 taken 16 times.
✗ Branch 1 not taken.
16 if (Y.dtype != ::brotensor::Dtype::FP32) {
106
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ fail(op, "Y must be FP32");
107 }
108
1/2
✓ Branch 0 taken 16 times.
✗ Branch 1 not taken.
16 if (Y.rows < 0 || Y.cols < 0) {
109
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ fail(op, "Y has negative dimension");
110 }
111 32 const std::size_t n = static_cast<std::size_t>(Y.rows) *
112 16 static_cast<std::size_t>(Y.cols);
113
3/4
✓ Branch 0 taken 12 times.
✓ Branch 1 taken 4 times.
✓ Branch 2 taken 12 times.
✗ Branch 3 not taken.
16 if (n != 0 && Y.data == nullptr) {
114
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ fail(op, "Y is uncommitted; pre-allocate before calling");
115 }
116 16 return n;
117 ✗ }
118
119 } // namespace
120
121 // ─── sine_source_forward ────────────────────────────────────────────────────
122 // The GPU kernels' arithmetic (mir_audio.cpp AU_SINE_CYC / AU_SINE_SRC):
123 // per-frame cycles kept in [0, 1), harmonic phase frac((h+1) cyc).
124 2 void sine_source_forward(const ::brotensor::Tensor& f0, const ::brotensor::Tensor& phase0,
125 const ::brotensor::Tensor& w, const ::brotensor::Tensor& b, int upsample,
126 float sample_rate, float sine_amp, float noise_std, float uv_std, uint64_t key,
127 ::brotensor::Tensor& Y) {
128 2 const int F = f0.cols, D = w.cols;
129 2 const float* f = f0.host_f32();
130 2 const float* ph = phase0.host_f32();
131 2 const float* wh = w.host_f32();
132 2 const float bias = b.host_f32()[0];
133 2 float* y = Y.host_f32_mut();
134 2 const float per_frame = static_cast<float>(upsample) / sample_rate;
135 2 const float inv_sr = 1.0f / sample_rate;
136 2 constexpr float kTwoPi = 6.28318530717958647692f;
137 2 float cur = 0.0f;
138
2/2
✓ Branch 0 taken 405 times.
✓ Branch 1 taken 2 times.
407 for (int fr = 0; fr < F; ++fr) {
139 405 const float fv = f[fr];
140 405 const bool voiced = fv > 0.0f;
141
2/2
✓ Branch 0 taken 120035 times.
✓ Branch 1 taken 405 times.
120440 for (int j = 0; j < upsample; ++j) {
142 120035 const int t = fr * upsample + j;
143 120035 const float cyc = cur + static_cast<float>(j + 1) * (fv * inv_sr);
144 120035 float acc = bias;
145
2/2
✓ Branch 0 taken 1080105 times.
✓ Branch 1 taken 120035 times.
1200140 for (int h = 0; h < D; ++h) {
146 1080105 const float n = philox_normal(key, static_cast<uint64_t>(t) * D + h);
147 float s;
148
2/2
✓ Branch 0 taken 926184 times.
✓ Branch 1 taken 153921 times.
1080105 if (voiced) {
149 926184 float x = static_cast<float>(h + 1) * cyc;
150 926184 x -= std::floor(x);
151 926184 s = std::sin(x * kTwoPi + ph[h]) * sine_amp + n * noise_std;
152 926184 } else {
153 153921 s = n * uv_std;
154 }
155 1080105 acc += wh[h] * s;
156 1080105 }
157 120035 y[t] = std::tanh(acc);
158 120035 }
159
2/2
✓ Branch 0 taken 58 times.
✓ Branch 1 taken 347 times.
405 if (voiced) {
160 347 cur += fv * per_frame;
161 347 cur -= std::floor(cur);
162 347 }
163 405 }
164 2 }
165
166 // ─── randn ──────────────────────────────────────────────────────────────────
167 6 void randn(uint64_t key, uint64_t counter, ::brotensor::Tensor& Y) {
168 6 const std::size_t n = check_y("randn", Y);
169
2/2
✓ Branch 0 taken 5 times.
✓ Branch 1 taken 1 time.
6 if (n == 0) return;
170 5 float* y = Y.host_f32_mut();
171
2/2
✓ Branch 0 taken 100352 times.
✓ Branch 1 taken 5 times.
100357 for (std::size_t i = 0; i < n; ++i) {
172 100352 y[i] = philox_normal(key, counter + static_cast<uint64_t>(i));
173 100352 }
174 6 }
175
176 // ─── rand_uniform ───────────────────────────────────────────────────────────
177 4 void rand_uniform(uint64_t key, uint64_t counter, ::brotensor::Tensor& Y) {
178 4 const std::size_t n = check_y("rand_uniform", Y);
179
2/2
✓ Branch 0 taken 3 times.
✓ Branch 1 taken 1 time.
4 if (n == 0) return;
180 3 float* y = Y.host_f32_mut();
181
2/2
✓ Branch 0 taken 100256 times.
✓ Branch 1 taken 3 times.
100259 for (std::size_t i = 0; i < n; ++i) {
182 100256 y[i] = philox_uniform(key, counter + static_cast<uint64_t>(i));
183 100256 }
184 4 }
185
186 // ─── rand_bernoulli ─────────────────────────────────────────────────────────
187 4 void rand_bernoulli(float p, uint64_t key, uint64_t counter,
188 ::brotensor::Tensor& Y) {
189 4 const char* op = "rand_bernoulli";
190
1/2
✓ Branch 0 taken 4 times.
✗ Branch 1 not taken.
4 if (!(p >= 0.0f && p <= 1.0f)) {
191
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ fail(op, "p must be in [0, 1]");
192 }
193 4 const std::size_t n = check_y(op, Y);
194
2/2
✓ Branch 0 taken 3 times.
✓ Branch 1 taken 1 time.
4 if (n == 0) return;
195 3 float* y = Y.host_f32_mut();
196
2/2
✓ Branch 0 taken 3 times.
✓ Branch 1 taken 150000 times.
150003 for (std::size_t i = 0; i < n; ++i) {
197 150000 const float u = philox_uniform(key, counter + static_cast<uint64_t>(i));
198 150000 y[i] = (u < p) ? 1.0f : 0.0f;
199 150000 }
200 4 }
201
202 // ─── randn_truncated ────────────────────────────────────────────────────────
203 2 void randn_truncated(float lo, float hi, uint64_t key, uint64_t counter,
204 ::brotensor::Tensor& Y) {
205 2 const char* op = "randn_truncated";
206
1/4
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
2 if (!(lo < hi)) fail(op, "lo must be < hi");
207 2 const std::size_t n = check_y(op, Y);
208
2/2
✓ Branch 0 taken 1 time.
✓ Branch 1 taken 1 time.
2 if (n == 0) return;
209 1 float* y = Y.host_f32_mut();
210 1 constexpr int kMaxRetries = 64;
211
2/2
✓ Branch 0 taken 50000 times.
✓ Branch 1 taken 1 time.
50001 for (std::size_t i = 0; i < n; ++i) {
212 50000 float z = 0.0f;
213
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 52402 times.
52402 for (int r = 0; r < kMaxRetries; ++r) {
214 104804 const uint64_t sub = counter + static_cast<uint64_t>(i) +
215 104804 static_cast<uint64_t>(r) *
216 52402 static_cast<uint64_t>(n);
217 52402 z = philox_normal(key, sub);
218
4/4
✓ Branch 0 taken 51199 times.
✓ Branch 1 taken 1203 times.
✓ Branch 2 taken 50000 times.
✓ Branch 3 taken 1199 times.
52402 if (z >= lo && z <= hi) break;
219 2402 }
220
1/2
✓ Branch 0 taken 50000 times.
✗ Branch 1 not taken.
50000 if (z < lo) z = lo;
221
1/2
✓ Branch 0 taken 50000 times.
✗ Branch 1 not taken.
50000 if (z > hi) z = hi;
222 50000 y[i] = z;
223 50000 }
224 2 }
225
226 } // namespace brotensor::detail::cpu
227