ZONOS3-Mini / host /main.cpp
mlboydaisuke's picture
Replace the Android runner with a faster one
9b130f3 verified
Raw History Blame Contribute Delete
12.5 kB
#include "core.hpp"
#include <iomanip>
#include "prefix.hpp"
constexpr int P=768, C=10, V=4098, STOP=4096, PAD=4097, H=1024;
using Rows=std::vector<Row>;
static_assert(sizeof(Row)==10*sizeof(int32_t));
struct Stage {
double seconds=0;
unsigned calls=0;
};
struct Timing {
using Clock=std::chrono::steady_clock;
bool enabled;
unsigned reused_rows=0;
Stage lm_load, decoder_load, prompt, generation, decoder;
template<class Function> void measure(Stage& stage, Function call) {
if (!enabled) {
call();
return;
}
auto start=Clock::now();
call();
stage.seconds+=std::chrono::duration<double>(Clock::now()-start).count();
++stage.calls;
}
void report(double wall) const {
const double host=wall-lm_load.seconds-decoder_load.seconds-prompt.seconds-generation.seconds-decoder.seconds;
std::cerr<<std::setprecision(17)<<"TIMING {\"threads\":4,\"wall_s\":"<<wall
<<",\"lm_load_s\":"<<lm_load.seconds<<",\"lm_loads\":"<<lm_load.calls
<<",\"decoder_load_s\":"<<decoder_load.seconds<<",\"decoder_loads\":"<<decoder_load.calls
<<",\"reused_prompt_rows\":"<<reused_rows<<",\"prompt_s\":"<<prompt.seconds<<",\"prompt_calls\":"<<prompt.calls
<<",\"generation_s\":"<<generation.seconds<<",\"generation_calls\":"<<generation.calls
<<",\"decoder_s\":"<<decoder.seconds<<",\"decoder_calls\":"<<decoder.calls
<<",\"speaker_s\":0,\"speaker_calls\":0,\"speaker_load_s\":0,\"speaker_loads\":0,\"host_total_s\":"<<host<<"}\n";
}
};
class Generation {
const fs::path shared;
Timing& timing;
Floats embeds, text_pad, cosines, sines;
Floats kv=Floats(4*3072*32), gdn=Floats(9*4*128*128), conv=Floats(9*3*1536);
Floats new_kv=Floats(4*4*32), mask=Floats(P+1);
std::unique_ptr<Graph> graph;
std::ifstream replay_logits, replay_x;
int pos=0;
public:
Floats logits=Floats(C*V);
Generation(const fs::path& s, const fs::path& lm, const fs::path& replay, Timing& stats):shared(s),timing(stats) {
embeds=read_file<float>(s/"embeddings.f32",C*V*H);
text_pad=read_file<float>(s/"text_pad.f32",H);
if (replay.empty()) {
timing.measure(timing.lm_load,[&]{graph=open_graph(lm,false);});
cosines=read_file<float>(s/"lm_cos.f32",P*16);
sines=read_file<float>(s/"lm_sin.f32",P*16);
} else {
replay_logits.open(replay/"logits.f32",std::ios::binary);
replay_x.open(replay/"rows.f32",std::ios::binary);
require(replay_logits && replay_x,"open replay");
}
}
void step(const float* x, Stage& stage) {
require(pos<P,"CapacityReached");
if (graph) {
std::fill(mask.begin(),mask.end(),-30000.f);
std::fill_n(mask.begin(),pos,0.f);
mask[P]=0.f;
timing.measure(stage,[&]{
graph->run({{x,H},{cosines.data()+pos*16,16},{sines.data()+pos*16,16},
view(mask),view(kv),view(gdn),view(conv)}, {&logits,&new_kv,&gdn,&conv});
});
for (int h=0; h<4; ++h)
for (int j=0; j<4; ++j)
std::copy_n(new_kv.data()+(h*4+j)*32,32,kv.data()+((h*4+j)*P+pos)*32);
} else {
float check[H];
require(bool(replay_x.read(reinterpret_cast<char*>(check),sizeof(check))),"missing replay row");
require(std::memcmp(check,x,sizeof(check))==0,"replay input row mismatch at "+std::to_string(pos));
require(bool(replay_logits.read(reinterpret_cast<char*>(logits.data()),logits.size()*4)), "missing logits");
}
++pos;
}
void prepare_prefix(const fs::path& path,const fs::path& lm,const Floats& prompt) {
auto key=prefix::key(lm,prompt,cosines,sines);
for (int i=0;i<prefix::rows;++i) step(prompt.data()+i*H,timing.prompt);
prefix::save(path,std::move(key),kv,gdn,conv);
}
void prefill(const Floats& prompt,const fs::path& path,const fs::path& lm) {
if (!path.empty() && prompt.size()>prefix::prefix_values &&
prefix::restore(path,prefix::key(lm,prompt,cosines,sines),kv,gdn,conv)) {
pos=prefix::rows;
timing.reused_rows=pos;
}
for (size_t i=size_t(pos)*H;i<prompt.size();i+=H) step(prompt.data()+i,timing.prompt);
}
void feed(const Row& row) {
Floats x(H);
for (int cb=0; cb<C; ++cb) {
auto e=embeds.data()+(cb*V+row[cb])*H;
for (int h=0; h<H; ++h) x[h] += e[h];
}
for (int h=0; h<H; ++h) x[h]+=text_pad[h];
step(x.data(),timing.generation);
}
void finish() {
if (!graph)
require(replay_logits.peek()==EOF && replay_x.peek()==EOF,"unused captured LM calls");
}
};
static Row sample(const Floats& logits, const Rows& generated, const Floats& draws) {
Row row{};
std::vector<int> order(STOP+1);
Floats x(STOP+1), weights(STOP+1);
for (int cb=0; cb<C; ++cb) {
std::array<bool,STOP> recent{};
if (cb<6) {
int begin=std::max(0,static_cast<int>(generated.size())-96);
for (size_t r=begin; r<generated.size(); ++r) {
int id=generated[r][cb];
if (id<STOP) recent[id]=true;
}
}
for (int id=0; id<=STOP; ++id) {
float value=logits[cb*V+id];
require(std::isfinite(value),"nonfinite logits");
if (id<STOP && recent[id]) value=value>0 ? value/2.4f : value*2.4f;
x[id]=value/0.75f;
}
std::iota(order.begin(),order.end(),0);
auto higher=[&](int a,int b){return x[a]==x[b] ? a<b : x[a]>x[b];};
std::nth_element(order.begin(),order.begin()+79,order.end(),higher);
float cutoff=x[order[79]];
auto end=std::partition(order.begin(),order.end(),[&](int i){return x[i]>=cutoff;});
std::sort(order.begin(),end,higher);
double total=0;
for (auto it=order.begin(); it!=end; ++it) {
weights[*it]=std::exp(x[*it]-x[order.front()]);
total+=weights[*it];
}
double prefix=0;
auto kept_end=end;
double kept_sum=0;
for (auto it=order.begin(); it!=end; ++it) {
int id=*it;
float probability=static_cast<float>(weights[id]/total);
prefix+=probability;
if (static_cast<float>(prefix)-probability>0.69f) {
kept_end=it;
break;
}
weights[id]=probability;
kept_sum+=probability;
}
float best=-1;
for (auto it=order.begin(); it!=kept_end; ++it) {
int id=*it;
float normalized=weights[id]/static_cast<float>(kept_sum);
float race=normalized/draws[cb*V+id];
if (race>best || (race==best && id<row[cb])) {
best=race;
row[cb]=id;
}
}
}
return row;
}
static Rows generate(const fs::path& take, const fs::path& shared, const fs::path& lm, const fs::path& replay, Timing& timing,const fs::path& cache) {
auto prompt=read_file<float>(take/"prompt.f32");
require(!prompt.empty() && prompt.size()%H==0 && prompt.size()/H<P,"invalid prompt rows");
auto silence=read_file<Row>(take/"silence.i32");
Generation gen(shared,lm,replay,timing);
gen.prefill(prompt,cache,lm);
std::ifstream stream(take/"draws.f32",std::ios::binary);
Floats draws(C*V);
Rows rows;
int eos=-1, countdown=-1;
// The kit specifies Savannah reference prompts with three delayed silence rows.
require(silence.size()==3,"expected Savannah silence prefix");
for (int n=0;; ++n) {
require(bool(stream.read(reinterpret_cast<char*>(draws.data()),draws.size()*4)),"draw stream exhausted");
auto accepted=sample(gen.logits,rows,draws);
rows.push_back(accepted);
for (int j=C-1; j>=0 && eos<0; --j) {
if (accepted[j]==STOP) { eos=std::max(0,n-j); countdown=C+1; }
}
if (countdown>0 && --countdown==0) break;
gen.feed(accepted);
}
gen.finish();
int prefill=silence.size(), target=prefill+eos;
for (int r=0; r<static_cast<int>(rows.size()); ++r)
for (int j=0; j<C; ++j)
if (rows[r][j]==STOP) target=std::min(target,std::max(0,prefill+r-j));
silence.insert(silence.end(),rows.begin(),rows.end());
target=std::min(target,static_cast<int>(silence.size())-C+1);
if (target<=prefill) return {};
require(target<=150,"BucketExceeded: "+std::to_string(target)+" frames");
Rows codes(target);
for (int t=0; t<target; ++t)
for (int j=0; j<C; ++j) {
codes[t][j]=silence[t+j][j];
require(codes[t][j]>=0 && codes[t][j]<STOP,"invalid undelayed code");
}
return codes;
}
static Floats decode(const Rows& codes,const fs::path& shared,const fs::path& model,const fs::path& replay,Timing& timing) {
if (codes.empty()) return {};
auto books=read_file<float>(shared/"books.f32",C*STOP*8);
Floats vectors(150*80);
for (size_t t=0; t<codes.size(); ++t)
for (int j=0; j<C; ++j)
std::copy_n(books.data()+(j*STOP+codes[t][j])*8,8,vectors.data()+t*80+j*8);
Floats head;
if (replay.empty()) {
std::vector<Floats> inputs;
inputs.push_back(std::move(vectors));
for (auto name:{"dec_cos.f32","dec_sin.f32"}) inputs.push_back(read_file<float>(shared/name,2400*32));
for (int i=0; i<5; ++i) {
int length=150<<i;
inputs.push_back(read_file<float>(shared/("window"+std::to_string(i)+".f32"),length*length));
}
for (int i=0; i<5; ++i) {
inputs.emplace_back(150<<i,0.f);
std::fill_n(inputs.back().begin(),codes.size()<<i,1.f);
}
std::vector<View> views;
for (auto& input:inputs) views.push_back(view(input));
head.resize(2400*2948);
std::unique_ptr<Graph> graph;
timing.measure(timing.decoder_load,[&]{graph=open_graph(model,true);});
timing.measure(timing.decoder,[&]{graph->run(views,{&head});});
} else {
require(vectors==read_file<float>(replay/"cv.f32",150*80),"replay codec input mismatch");
head=read_file<float>(replay/"head.f32",2400*2948);
}
return decode_audio(head,codes.size(),shared);
}
int main(int argc,char** argv) {
try {
Timing timing{argc>1 && std::string(argv[1])=="--timing"};
if (timing.enabled) { --argc; ++argv; }
if (argc==6 && std::string(argv[1])=="--prepare-prefix") {
const auto start=Timing::Clock::now();
fs::path kit=argv[3],lm=argv[5];
Generation gen(kit/"shared",lm,{},timing);
gen.prepare_prefix(argv[2],lm,read_file<float>(kit/"takes"/argv[4]/"prompt.f32"));
std::cerr<<"PREFIX rows="<<prefix::rows<<" bytes="<<fs::file_size(argv[2])
<<" seconds="<<std::chrono::duration<double>(Timing::Clock::now()-start).count()<<"\n";
return 0;
}
fs::path cache;
if (argc>2 && std::string(argv[1])=="--prefix-cache") { cache=argv[2]; argv+=2; argc-=2; }
require(argc==6 || (argc==7 && cache.empty()),"usage: zonos_host [--timing] [--prefix-cache FILE] KIT TAG LM_GRAPH DEC_GRAPH OUTPUT [REPLAY_TAKE_DIR]");
fs::path kit=argv[1], dest=argv[5], replay=argc==7 ? argv[6] : "";
auto shared=kit/"shared", take=kit/"takes"/argv[2];
require(!fs::exists(dest),"output directory already exists");
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
const auto start=std::chrono::steady_clock::now();
auto codes=generate(take,shared,argv[3],replay,timing,cache);
auto wave=decode(codes,shared,argv[4],replay,timing);
fs::create_directories(dest);
write_file(dest/"codes.i32",codes);
save_audio(dest,wave);
double seconds=std::chrono::duration<double>(std::chrono::steady_clock::now()-start).count();
std::cerr<<"TAKE "<<argv[2]<<" frames="<<codes.size()<<" samples="<<wave.size()<<" wall_s="<<seconds<<"\n";
if (timing.enabled) timing.report(seconds);
return 0;
} catch (const std::exception& e) {
std::cerr<<"TAKE_ERROR "<<e.what()<<"\n";
return 1;
}
}