[gen~] additive synthesis efficiency problem
A student used an LLM to populate a gen~ with an additive approach to plucked string synthesis.
It's a bit CPU-heavier than I'd like (well, kind of a lot CPU heavier, particularly if the goal is to introduce polyphony later).
An "elapsed" counter is initialized when a trigger signal is received ("prev <= 0 && now > 0"); otherwise, it's incremented by 1/sr. Then a loop drives it:
limit = min(20000, f1*256);
i = 1;
for (fn = f1; fn < limit; fn += f1) {
i += 1;
// Modal force amplitude
an = sign * K * sin(i * 3.14159265359 * p) / i;
// Individual decay time
dn = tau0 * pitchDecay / pow(i, alpha);
// Modal oscillation and exponential decay
sn = an * exp(-elapsed / dn)
* cos(6.28318530718 * fn * elapsed);
// Accumulate
sum = sum + sn;
}I'm leaving out a few details that are not relevant to the code structure.
I'm not sure of the relationship between the code box contents and the eventual llvm stuff, so I'm at a bit of a loss to suggest how to make it more efficient. If it were standard imperative code, I would perhaps cache the 'an' values and not do sin() every time, and replace the pow and exp with cascaded multiplications. Not sure how gen~ handles those.
Any ideas?
hjh
sin() ist very cheap on modern processors, given that the poor thing might end up in a [poly~ foo up 16] i don´t think a lookuptable will be any better.
Computers really don't like division. I would see if you can replace them with multipliers especially when used in heavy math functions such as here. If you know the limit its 1/n before your loop and just multiply it by i*1/n within the loop itself.
Source:
https://cycling74.com/forums/need-help-cleaning-up-a-gen-patch
At one point in the thread here i removed 8-ish divi...ders? and got a performance increase of 10% in that case so that was pretty convincing of the benefit of doing so
sin, cos, pow, exp are all very expensive to calculate.
For sin and cos, you can use cycle~ with index input for a cheaper (co)sine lookup table. For your pow/exp calculations there might be other approximations or lookup tables that you can generate once in a data() object.
Thanks for those. I'm seeing a bit of CPU savings with this modification:
an = sign * K * cycle((i * halfP) + 0.25, index="phase") / i;
// Individual decay time
// but inverted to save a divider below
dn = pow(i, alpha) / (tau0 * pitchDecay);
// Modal oscillation and exponential decay
sn = an * exp(-elapsed * dn)
* cycle(fn * elapsed, index="phase");But it's only a few percentage points, supporting Roman's point that sin isn't so terribly expensive on modern machines.
pow and exp here would have to rely on lookup tables because they aren't being called with a constant time increment. pow is 1^alpha, 2^alpha, 3^alpha etc. In exp, elapsed is constant and dn is not linearly increasing. Estimating these is more than I'm going to get into this afternoon.
Question: Does gen~ always evaluate sample by sample? If so, then a major inefficiency is that, for n harmonics, it must individually calculate the coefficients for each harmonic for every sample. In SC, there are externals DynGen and (in development) OndaCollider, whose code blocks can have init, block and sample sections. I would love to be able to calculate these coefficients per block and then reuse them for multiple samples. Then, for instance, it would be possible to calculate, for a given dn, the ratio between exp(next_sample) / exp(start_of_block_sample) and then simply multiply the envelope value by this ratio for each sample. So 64 exp calls turn into 2 per block. I'm certain this would save some CPU cycles.
I'm guessing this is not supported, but it's worth asking.
TIA,
hjh
yes, when the blocksize in gen~ is 1 sample this means that things are actually processed sample by sample by the processor (and not like the outer MSP world with their blocksize.)
only later when it is given back to MSP, that will happen in MSP vectors again.
in theory you might be able multiplex 4 samples into sample position #4 and have a multiplication or addition to your samples SIMD´ed, but that will cause 3 samples latency of the gen~ patcher and you could as well do it in MSP. :)
For clarification, it is true that most operations in gen~ operate at sample rate, but this isn't always true. The gen~ compiler will try to hoist any operations to block rate if that is possible without changing the resulting behaviour, in order to save CPU.
Specifically, any pure math operations on [param] objects, buffer/data [dim], [samplerate] and [blocksize] parameters will only operate at block rate. For example, if you have a [param decay_ms 1000] and you send that through a [mstosamps] or [t60] or [!/ 1.] or similar simple math, then those operations will only happen at block rate, not at sample rate. That will keep going until you hit an operation that involves an audio rate signal or operation, which means anything downstream of an [in], [noise~], etc., or any operation that is inherently audio rate like [history], [delta], [cycle], [delay], etc. If using codebox, this also applies, but anything inside an if, while, etc. control flow structure will also be audio rate.
For example, from the code in the original post:
limit = min(20000, f1*256);If f1 is a param, then this entire operation will compute once per block, not once per sample. But if f1 comes from an `in1` or similar, then it will be computed at audio rate. Meanwhile, everything inside the for loop will be computed once per sample.
So, one way to save CPU is to use param wherever you can afford to (wherever things don't need to be audio rate), and lift as much out of the for loop as you can, if you can.
A few other suggestions on that code:
exp(-elapsed / dn)
elapsed is a reserved word in gen~. It is a sample counter that starts at 0 when the patcher is loaded or reset, and increases by 1 per sample. I'm not sure that's what you want to use for a resonator. (Note also that sign is a reserved word too -- it is the signum operation. And also gen~ has defined constants for pi and twopithat you can use! LLMs aren't always trustworthy sources...)
The exp^N usage here could actually be achieved using a recursive operation instead. It is just an exponential decay, which means multiplying by some constant (between 0 and 1, typically close to 1) on every sample.
Here's a single exponential decay:
History env;
Param decay_ms;
// this will all be computed at block rate:
tau = mstosamps(decay_ms); // convert decay time to time constant in samples
decay_factor = exp(-1/tau); // convert tau to a per-sample multiplier
// this involves History and in1, so it will be computed at sample rate:
env = env * decay_factor; // exponential decay of envelope
env = env + in1; // add input, e.g. from [click~], to trigger the envelope
out1 = env;You can modify that to scale by pitch too, and it will be a lot cheaper than computing it at audio rate.
There's some other options for faster cos/sin -- you can try the fastsin and fastcos operators, which are polynomial approximations based on truncated Taylor series.
That said, there's a much cheaper option to compute a decaying sinusoid that avoids needing audio-rate trigonometry or lookup tables, and that's to use a matrix operation. You can reconstruct an exact sinusoidal waveform using only multiplications and additions to perform matrix rotation of a vector. It is essentially the same as the core of a resonator filter.
Here's a single decaying oscillator:
Param freq(100);
Param decay(10);
History x, y; // the state of the system
// block rate calculation of coefficients:
omega = freq * twopi / samplerate;
r = exp(-decay/samplerate); // scaling factor per sample
c0 = r*cos(omega); // matrix components
c1 = r*sin(omega);
// audio rate operation, applies the rotation & scale operation
x1 = x*c0 - y*c1;
y1 = x*c1 + y*c0;
// reset system on an input trigger (e.g. from a [click~])
if (in1) {
x1, y1 = 1, 0;
}
// output:
out1, out2 = x1, y1;
// update histories;
x = x1;
y = y1;Notice that there are no expensive calls to trigonometry, exponential/power or division operations in the audio-rate operations. Yet, the result is going to be indistinguishable from doing sin() and exp() calls.
An added advantage (which you can ignore if you don't need it) is that the output is a quadrature pair of signals. Feel free to throw either away. The `y1` output may be preferable because it starts at zero, rather than at a clicky 1.
Now, you can't just throw this into a for loop, because it uses History objects. Every single resonator needs its own pair of state values x and y.
The simplest solution to this is to use a Data object to store the states instead. If you do that, then probably you also want to store the coefficients in the Data too.
// the state of the system: 256 resonators with values x, y, c0, c1
Data resonators(256, 4);
// this if() block only runs when the patch loads:
if (elapsed == 0) {
// loop over the list of resonators to initialize them:
for (i=0; i<256; i+=1) {
// TODO: compute freq and decay for resonator i however you prefer
// convert to sample rate resonator matrix coefficients:
omega = freq * twopi / samplerate;
r = exp(-decay/samplerate); // scaling factor per sample
c0 = r*cos(omega); // matrix components
c1 = r*sin(omega);
// initialize the Data channels for this resonator
poke(resonators, 0, i, 0); // x (begin silent)
poke(resonators, 0, i, 0); // y (begin silent)
poke(resonators, c0, i, 0); // c0
poke(resonators, c0, i, 0); // c1
}
// audio rate operation
sumx, sumy = 0, 0;
// loop over the list of resonators:
for (i=0; i<256; i+=1) {
// get this resonator:
x, y, c0, c1 = peek(resonators, i, channels=4);
// apply the rotation & scaling process:
x1 = x*c0 - y*c1;
y1 = x*c1 + y*c0;
// reset system on an input trigger (e.g. from a [click~])
if (in1) {
x1, y1 = 1, 0;
}
// output:
sumx += x1;
sumy += y1;
// update state
poke(resonators, x1, i, 0);
poke(resonators, y1, i, 1);
}
out1, out2 = sumx, sumy;
y = y1;There are no expensive math operations in that for loop at all. The only slightly expensive operations are the data reads & writes.
You can also write code to ping any individual resonator, rather than all of them at once, by poking the corresponding part of the resonators data. Similarly, you can re-tune any individual resonator in response to some param change, etc. It's quite flexible.
Quick example:
The sovereign power of the master doth cause his disciples to freeze in profound dread and reverence.