matthiastl's picture
TYGER for iPhone (Core ML, Neural Engine)
d65bf0f
Raw History Blame Contribute Delete
15.4 kB
#import "Bench.h"
#import <CoreML/CoreML.h>
#import <Foundation/Foundation.h>
#include <Accelerate/Accelerate.h>
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <math.h>
#include <onnxruntime/onnxruntime_c_api.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Log-mels as l15.LogMel: pre-emphasis 0.97, centred 512-point STFT of a 400-sample symmetric Hann window every 160
samples, power, 128 mels, log(x + 2^-24), the last frame (past the audio) zeroed. */
#define N_FFT 512
#define N_BINS 257
#define N_MELS 128
#define MEL_HOP 160
#define WINDOW_N 128000 /* 8 s */
#define MAX_MEL (WINDOW_N / MEL_HOP + 1)
#define D 1024
#define ENC_FRAMES 101
#define GRU_STATE (3 * 768)
typedef struct {
float window[N_FFT];
float *cos_basis, *sin_basis; /* (512, 257) */
const float *filters; /* (128, 257) */
float padded[WINDOW_N + N_FFT];
float frames[MAX_MEL * N_FFT];
float re[MAX_MEL * N_BINS], im[MAX_MEL * N_BINS];
float mel[MAX_MEL * N_MELS];
} Mel;
typedef struct {
float window[WINDOW_N];
int n;
float newest[TYGER_HOP_FRAMES * D];
} Stream;
static char error_text[512];
static mach_timebase_info_data_t timebase(void) {
static mach_timebase_info_data_t t;
if (t.denom == 0) mach_timebase_info(&t);
return t;
}
static double now_ms(void) {
mach_timebase_info_data_t t = timebase();
return (double)mach_absolute_time() * t.numer / t.denom / 1e6;
}
static void sleep_until_ms(double ms) {
mach_timebase_info_data_t t = timebase();
mach_wait_until((uint64_t)(ms * 1e6 * t.denom / t.numer));
}
void tyger_memory(double *now_mb, double *peak_mb) {
task_vm_info_data_t info;
mach_msg_type_number_t count = TASK_VM_INFO_COUNT;
memset(&info, 0, sizeof info);
task_info(mach_task_self(), TASK_VM_INFO, (task_info_t)&info, &count);
*now_mb = info.phys_footprint / 1e6;
*peak_mb = info.ledger_phys_footprint_peak / 1e6;
}
static void mel_init(Mel *m, const float *filters) {
for (int n = 0; n < 400; n++) m->window[56 + n] = (float)(0.5 - 0.5 * cos(2 * M_PI * n / 399));
m->cos_basis = malloc(sizeof(float) * N_FFT * N_BINS);
m->sin_basis = malloc(sizeof(float) * N_FFT * N_BINS);
for (int j = 0; j < N_FFT; j++)
for (int k = 0; k < N_BINS; k++) {
double a = 2 * M_PI * (double)((j * k) % N_FFT) / N_FFT;
m->cos_basis[j * N_BINS + k] = (float)cos(a);
m->sin_basis[j * N_BINS + k] = (float)sin(a);
}
m->filters = filters;
}
/* wav (n samples) -> m->mel, (returned frame count, 128). */
static int log_mel(Mel *m, const float *wav, int n) {
memset(m->padded, 0, sizeof(float) * (n + N_FFT));
float *x = m->padded + N_FFT / 2;
x[0] = wav[0];
for (int i = 1; i < n; i++) x[i] = wav[i] - 0.97f * wav[i - 1];
int frames = 1 + n / MEL_HOP;
for (int f = 0; f < frames; f++)
vDSP_vmul(m->padded + f * MEL_HOP, 1, m->window, 1, m->frames + f * N_FFT, 1, N_FFT);
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, frames, N_BINS, N_FFT, 1.0f, m->frames, N_FFT,
m->cos_basis, N_BINS, 0.0f, m->re, N_BINS);
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, frames, N_BINS, N_FFT, 1.0f, m->frames, N_FFT,
m->sin_basis, N_BINS, 0.0f, m->im, N_BINS);
int count = frames * N_BINS;
vDSP_vmma(m->re, 1, m->re, 1, m->im, 1, m->im, 1, m->re, 1, count); /* power = re^2 + im^2 */
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, frames, N_MELS, N_BINS, 1.0f, m->re, N_BINS,
m->filters, N_BINS, 0.0f, m->mel, N_MELS);
for (int i = 0; i < frames * N_MELS; i++) m->mel[i] = logf(m->mel[i] + 5.9604644775390625e-8f);
for (int f = n / MEL_HOP; f < frames; f++) memset(m->mel + f * N_MELS, 0, sizeof(float) * N_MELS);
return frames;
}
static void frame_energy(const float *hop, float *db) {
int n = TYGER_HOP_N / TYGER_HOP_FRAMES;
for (int f = 0; f < TYGER_HOP_FRAMES; f++) {
float mean = 0;
vDSP_measqv(hop + f * n, 1, &mean, n);
db[f] = 20.0f * log10f(sqrtf(mean + 1e-12f) + 1e-9f);
}
}
#define CHECK(call) \
do { \
OrtStatus *status_ = (call); \
if (status_ != NULL) { \
snprintf(error_text, sizeof error_text, "%s", ort->GetErrorMessage(status_)); \
ort->ReleaseStatus(status_); \
failed = 1; \
goto done; \
} \
} while (0)
int tyger_plan(const char *l15_path, int *neural_engine, int *gpu, int *cpu) {
__block int ok = 0, n_ane = 0, n_gpu = 0, n_cpu = 0;
if (@available(iOS 17.4, *)) {
@autoreleasepool {
MLModelConfiguration *config = [MLModelConfiguration new];
config.computeUnits = MLComputeUnitsCPUAndNeuralEngine;
dispatch_semaphore_t done = dispatch_semaphore_create(0);
[MLComputePlan loadContentsOfURL:[NSURL fileURLWithPath:@(l15_path)] configuration:config
completionHandler:^(MLComputePlan *plan, NSError *error) {
MLModelStructureProgramFunction *main = plan.modelStructure.program.functions[@"main"];
for (MLModelStructureProgramOperation *op in main.block.operations) {
MLComputePlanDeviceUsage *usage = [plan computeDeviceUsageForMLProgramOperation:op];
if (usage == nil) continue;
ok = 1;
id device = usage.preferredComputeDevice;
if ([device isKindOfClass:[MLNeuralEngineComputeDevice class]]) n_ane++;
else if ([device isKindOfClass:[MLGPUComputeDevice class]]) n_gpu++;
else n_cpu++;
}
dispatch_semaphore_signal(done);
}];
dispatch_semaphore_wait(done, DISPATCH_TIME_FOREVER);
}
}
*neural_engine = n_ane; *gpu = n_gpu; *cpu = n_cpu;
return ok;
}
static void fill_input(__fp16 *slot, const Mel *mel, int frames) {
for (int i = 0; i < frames * N_MELS; i++) slot[i] = (__fp16)mel->mel[i];
memset(slot + frames * N_MELS, 0, sizeof(__fp16) * (MAX_MEL - frames) * N_MELS);
}
/* The model on its input -> each stream's newest 4 frames of the `frames` real ones. `count` windows in the input. */
static NSString *predict(MLModel *model, id<MLFeatureProvider> in, int frames, int count, float *const *newest) {
NSError *error = nil;
id<MLFeatureProvider> out = [model predictionFromFeatures:in error:&error];
if (out == nil) return error.localizedDescription ?: @"prediction failed";
MLMultiArray *y = [out featureValueForName:@"l15"].multiArrayValue;
if (y == nil || y.dataType != MLMultiArrayDataTypeFloat16 || y.shape.count != 3 || y.shape[0].intValue != count
|| y.shape[1].intValue != ENC_FRAMES || y.shape[2].intValue != D) return [NSString stringWithFormat:@"encoder gave %@", y.shape];
NSInteger block = y.strides[0].integerValue, row = y.strides[1].integerValue, col = y.strides[2].integerValue;
int last = (frames - 1) / 8 + 1;
__block NSString *problem = nil;
[y getBytesWithHandler:^(const void *bytes, NSInteger size) {
const __fp16 *data = bytes;
if ((count - 1) * block + (last - 1) * row + (D - 1) * col >= size / (NSInteger)sizeof(__fp16)) { problem = @"output too small"; return; }
for (int s = 0; s < count; s++)
for (int f = 0; f < TYGER_HOP_FRAMES; f++)
for (int d = 0; d < D; d++) newest[s][f * D + d] = data[s * block + (last - TYGER_HOP_FRAMES + f) * row + d * col];
}];
return problem;
}
const char *tyger_run(const char *l15_path, const char *gru_path, const float *mel_filters, const float *user,
const float *agent, int audio_hops, int hops, int threads, int previous_state, int paced,
float *hop_ms, float *delay_ms, float *encode_ms, float *outputs, double *load_ms) {
MLModel *model = nil;
id<MLFeatureProvider> feature = nil;
NSError *error = nil;
__fp16 *input = NULL;
int batch = 1; /* windows per prediction, from the model's input: 1, or both streams */
if (posix_memalign((void **)&input, 16384, sizeof(__fp16) * 2 * MAX_MEL * N_MELS) != 0) return "no memory";
memset(input, 0, sizeof(__fp16) * 2 * MAX_MEL * N_MELS);
@autoreleasepool {
MLModelConfiguration *config = [MLModelConfiguration new];
config.computeUnits = MLComputeUnitsCPUAndNeuralEngine;
double load_start = now_ms();
model = [MLModel modelWithContentsOfURL:[NSURL fileURLWithPath:@(l15_path)] configuration:config error:&error];
*load_ms = now_ms() - load_start;
if (model != nil) {
batch = model.modelDescription.inputDescriptionsByName[@"mel"].multiArrayConstraint.shape[0].intValue;
MLMultiArray *x = [[MLMultiArray alloc] initWithDataPointer:input shape:@[@(batch), @(MAX_MEL), @(N_MELS)]
dataType:MLMultiArrayDataTypeFloat16 strides:@[@(MAX_MEL * N_MELS), @(N_MELS), @1] deallocator:nil error:&error];
if (x != nil) feature = [[MLDictionaryFeatureProvider alloc] initWithDictionary:@{@"mel": x} error:&error];
}
if (feature == nil) {
snprintf(error_text, sizeof error_text, "Core ML: %s", (error.localizedDescription ?: @"could not load").UTF8String);
free(input);
return error_text;
}
}
const OrtApi *ort = OrtGetApiBase()->GetApi(ORT_API_VERSION);
OrtEnv *env = NULL;
OrtSessionOptions *options = NULL;
OrtSession *gru = NULL;
OrtMemoryInfo *memory = NULL;
OrtValue *gru_state = NULL;
float *gru_zeros = calloc(GRU_STATE, sizeof(float));
Mel *mel = calloc(1, sizeof(Mel));
Stream *streams = calloc(2, sizeof(Stream));
const float *audio[2] = {user, agent};
int failed = 0;
const int64_t one[] = {1}, vec_shape[] = {1, D}, gru_shape[] = {3, 1, 768};
const char *gru_in[] = {"user", "agent", "energy_db", "previous_state", "state_in"};
const char *gru_out[] = {"outputs", "state_out"};
mel_init(mel, mel_filters);
CHECK(ort->CreateEnv(ORT_LOGGING_LEVEL_WARNING, "tygercoreml", &env));
CHECK(ort->CreateSessionOptions(&options));
CHECK(ort->SetIntraOpNumThreads(options, threads));
CHECK(ort->SetInterOpNumThreads(options, 1));
CHECK(ort->SetSessionExecutionMode(options, ORT_SEQUENTIAL));
CHECK(ort->SetSessionGraphOptimizationLevel(options, ORT_ENABLE_ALL));
CHECK(ort->CreateSession(env, gru_path, options, &gru));
CHECK(ort->CreateCpuMemoryInfo(OrtArenaAllocator, OrtMemTypeDefault, &memory));
CHECK(ort->CreateTensorWithDataAsOrtValue(memory, gru_zeros, sizeof(float) * GRU_STATE, gru_shape, 3,
ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, &gru_state));
double live_start = now_ms();
for (int k = 0; k < hops; k++) {
double arrival = live_start + (k + 1) * 320.0;
if (paced && now_ms() < arrival) sleep_until_ms(arrival);
double start = now_ms();
const size_t at = (size_t)(k % audio_hops) * TYGER_HOP_N;
encode_ms[k] = 0;
for (int s = 0; s < 2; s++) {
Stream *st = &streams[s];
if (st->n + TYGER_HOP_N > WINDOW_N) {
memmove(st->window, st->window + TYGER_HOP_N, sizeof(float) * (WINDOW_N - TYGER_HOP_N));
st->n = WINDOW_N - TYGER_HOP_N;
}
memcpy(st->window + st->n, audio[s] + at, sizeof(float) * TYGER_HOP_N);
st->n += TYGER_HOP_N;
int frames = log_mel(mel, st->window, st->n);
double encode_start = now_ms();
fill_input(input + (batch == 2 ? s * MAX_MEL * N_MELS : 0), mel, frames);
if (batch == 1 || s == 1) @autoreleasepool {
float *both[2] = {streams[0].newest, streams[1].newest}, *single[1] = {st->newest};
NSString *problem = predict(model, feature, frames, batch, batch == 2 ? both : single);
if (problem != nil) {
snprintf(error_text, sizeof error_text, "Core ML: %s", problem.UTF8String);
failed = 1;
}
}
if (failed) goto done;
encode_ms[k] += (float)(now_ms() - encode_start);
}
float db[TYGER_HOP_FRAMES];
frame_energy(user + at, db);
int64_t prev = previous_state;
for (int i = 0; i < TYGER_HOP_FRAMES; i++) {
OrtValue *u = NULL, *a = NULL, *e = NULL, *p = NULL, *out[2] = {NULL, NULL};
CHECK(ort->CreateTensorWithDataAsOrtValue(memory, streams[0].newest + i * D, sizeof(float) * D, vec_shape,
2, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, &u));
CHECK(ort->CreateTensorWithDataAsOrtValue(memory, streams[1].newest + i * D, sizeof(float) * D, vec_shape,
2, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, &a));
CHECK(ort->CreateTensorWithDataAsOrtValue(memory, &db[i], sizeof(float), one, 1,
ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, &e));
CHECK(ort->CreateTensorWithDataAsOrtValue(memory, &prev, sizeof prev, one, 1,
ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64, &p));
const OrtValue *in[] = {u, a, e, p, gru_state};
CHECK(ort->Run(gru, NULL, gru_in, in, 5, gru_out, 2, out));
float *o = NULL;
CHECK(ort->GetTensorMutableData(out[0], (void **)&o));
if (outputs != NULL)
memcpy(outputs + ((size_t)k * TYGER_HOP_FRAMES + i) * TYGER_OUTPUTS, o, sizeof(float) * TYGER_OUTPUTS);
ort->ReleaseValue(u);
ort->ReleaseValue(a);
ort->ReleaseValue(e);
ort->ReleaseValue(p);
ort->ReleaseValue(out[0]);
ort->ReleaseValue(gru_state);
gru_state = out[1];
}
double end = now_ms();
hop_ms[k] = (float)(end - start);
delay_ms[k] = paced ? (float)(end - arrival) : hop_ms[k];
if (k % 25 == 24) {
printf("TYGERPHONE_PROGRESS%s hop %d of %d: %.1f ms, delay %.1f ms\n",
paced ? " live" : "", k + 1, hops, hop_ms[k], delay_ms[k]);
fflush(stdout);
}
}
done:
if (gru_state != NULL) ort->ReleaseValue(gru_state);
if (memory != NULL) ort->ReleaseMemoryInfo(memory);
if (gru != NULL) ort->ReleaseSession(gru);
if (options != NULL) ort->ReleaseSessionOptions(options);
if (env != NULL) ort->ReleaseEnv(env);
free(input);
free(mel->cos_basis);
free(mel->sin_basis);
free(mel);
free(streams);
free(gru_zeros);
return failed ? error_text : NULL;
}