File size: 9,062 Bytes
2e0d354
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
#include "core.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));

class Generation {
    const fs::path shared;
    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):shared(s) {
        embeds=read_file<float>(s/"embeddings.f32",C*V*H);
        text_pad=read_file<float>(s/"text_pad.f32",H);
        if (replay.empty()) {
            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) {
        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;
            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 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());
    }
    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) {
    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);
    for (size_t i=0; i<prompt.size(); i+=H) gen.step(prompt.data()+i);
    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) {
    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);
        open_graph(model,true)->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 {
        require(argc==6 || argc==7,"usage: zonos_host 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);
        auto wave=decode(codes,shared,argv[4],replay);
        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";
        return 0;
    } catch (const std::exception& e) {
        std::cerr<<"TAKE_ERROR "<<e.what()<<"\n";
        return 1;
    }
}