// generate.cpp — генерация текста с KV-кэшем + диалоговый режим. // // Что здесь появилось/изменено относительно 0.0.4: // * исправлен sample(): top-k больше не отключается молча и не оставляет k+1 токен, // top-p нормируется корректно (был O(V²) std::find и неверная сумма), // repeat_penalty действительно применяется (был перезаписан сразу после вычисления); // * исправлен слайд контекста: было чтение за границей вектора // (ids[i] = ids[ids.size() - keep + i] при i >= keep) и расхождение kv.len/ids; // * generate_from() — генерация из произвольной истории токенов, ядро для всего; // * chat_turn() — диалоговый ход: подставляет /, останавливается // на , ведёт историю между вызовами; // * колбэк на каждый токен — чтобы HTTP-сервер Ollama мог стримить NDJSON. #include "generate.h" #include #include #include #include #include namespace xt { namespace gen_impl { // --------------------------------------------------------------------------- // KV-кэш // --------------------------------------------------------------------------- struct KvCache { int n_layer = 0, max_ctx = 0, n_head = 0, head_dim = 0, d_model = 0; std::vector data; int len = 0; void init(int L, int ctx, int H, int hd) { n_layer = L; max_ctx = ctx; n_head = H; head_dim = hd; d_model = H * hd; const size_t per = (size_t)L * (size_t)ctx * (size_t)H * (size_t)hd; data.assign(per * 2, 0.0f); len = 0; } void reset() { len = 0; } size_t off(int L, int pos, int h) const { // граница обязательна: без неё рассинхрон kv.len тихо пишет мимо буфера if (pos < 0 || pos >= max_ctx || L < 0 || L >= n_layer || h < 0 || h >= n_head) { fprintf(stderr, "KvCache::off: выход за границы (L=%d pos=%d h=%d, max_ctx=%d)\n", L, pos, h, max_ctx); std::abort(); } return ((size_t)L * (size_t)max_ctx + (size_t)pos) * (size_t)n_head * (size_t)head_dim + (size_t)h * (size_t)head_dim; } float* K(int L, int pos, int h) { return data.data() + off(L, pos, h); } float* V(int L, int pos, int h) { return data.data() + data.size() / 2 + off(L, pos, h); } }; // --------------------------------------------------------------------------- // Скретч-буферы forward_token: аллоцируются один раз на сессию генерации, // а не на каждый токен (в 0.0.4 внутри функции создавалось ~16 Tensor на токен). // --------------------------------------------------------------------------- struct FwdScratch { Tensor x, xb, q, k, v, attout, proj, x2b, h1, h3, ha, fo, scores, ln, lnf, logits; bool ready = false; void alloc(const Config& c) { const int d = c.n_embd, f = c.ffn(); x.resize(1, d); xb.resize(1, d); q.resize(1, d); k.resize(1, d); v.resize(1, d); attout.resize(1, d); proj.resize(1, d); x2b.resize(1, d); h1.resize(1, f); h3.resize(1, f); ha.resize(1, f); fo.resize(1, d); ln.resize(1, 1); lnf.resize(1, d); logits.resize(1, c.vocab_out()); ready = true; } }; void rope_apply(float* x, int hd, int pos, const std::vector& cs, const std::vector& sn) { const int half = hd / 2; const float* c = cs.data() + (size_t)pos * (size_t)half; const float* s = sn.data() + (size_t)pos * (size_t)half; for (int i = 0; i < half; ++i) { const float c0 = c[i], s0 = s[i]; const float a = x[2 * i], b = x[2 * i + 1]; x[2 * i] = a * c0 - b * s0; x[2 * i + 1] = a * s0 + b * c0; } } // Прогнать ОДИН токен через модель, дописав его K/V в кэш. // pos — позиция токена; logits получает распределение СЛЕДУЮЩЕГО токена. void forward_token(const Params& p, KvCache& kv, FwdScratch& sc, int token, int pos, const std::vector& cs, const std::vector& sn, Tensor& logits) { const Config& c = p.cfg; const int d = c.n_embd, H = c.n_head, hd = c.head_dim(), f = c.ffn(); const float scale = 1.0f / std::sqrt((float)hd); if (!sc.ready) sc.alloc(c); if (token < 0 || token >= c.vocab_size) token = 0; // защита от мусорного id const float* er = p.wte.row(token); float* xr = sc.x.row(0); for (int j = 0; j < d; ++j) xr[j] = er[j]; sc.scores.resize(1, pos + 1); for (int L = 0; L < c.n_layer; ++L) { rmsnorm_forward(sc.x, p.rms_attn[L], c.rms_eps, sc.xb, sc.ln); gemm_nn(sc.xb, p.wq[L], sc.q); gemm_nn(sc.xb, p.wk[L], sc.k); gemm_nn(sc.xb, p.wv[L], sc.v); for (int h = 0; h < H; ++h) { rope_apply(sc.q.row(0) + h * hd, hd, pos, cs, sn); rope_apply(sc.k.row(0) + h * hd, hd, pos, cs, sn); float* kp = kv.K(L, pos, h); float* vp = kv.V(L, pos, h); const float* ksrc = sc.k.row(0) + h * hd; const float* vsrc = sc.v.row(0) + h * hd; for (int j = 0; j < hd; ++j) { kp[j] = ksrc[j]; vp[j] = vsrc[j]; } } sc.attout.zero(); for (int h = 0; h < H; ++h) { const float* qr = sc.q.row(0) + h * hd; float mx = -1e30f; float* sr = sc.scores.row(0); for (int t = 0; t <= pos; ++t) { const float* kr = kv.K(L, t, h); float s = 0.0f; for (int j = 0; j < hd; ++j) s += qr[j] * kr[j]; s *= scale; sr[t] = s; mx = std::max(mx, s); } float sum = 0.0f; for (int t = 0; t <= pos; ++t) { sr[t] = std::exp(sr[t] - mx); sum += sr[t]; } const float inv = 1.0f / std::max(sum, 1e-30f); float* orow = sc.attout.row(0) + h * hd; for (int t = 0; t <= pos; ++t) { const float a = sr[t] * inv; const float* vr = kv.V(L, t, h); for (int j = 0; j < hd; ++j) orow[j] += a * vr[j]; } } gemm_nn(sc.attout, p.wo[L], sc.proj); for (int j = 0; j < d; ++j) xr[j] += sc.proj.at(j); rmsnorm_forward(sc.x, p.rms_ffn[L], c.rms_eps, sc.x2b, sc.ln); gemm_nn(sc.x2b, p.w1[L], sc.h1); gemm_nn(sc.x2b, p.w3[L], sc.h3); float* har = sc.ha.row(0); for (int j = 0; j < f; ++j) har[j] = silu(sc.h1.at(j)) * sc.h3.at(j); gemm_nn(sc.ha, p.w2[L], sc.fo); for (int j = 0; j < d; ++j) xr[j] += sc.fo.at(j); } rmsnorm_forward(sc.x, p.rms_final, c.rms_eps, sc.lnf, sc.ln); if (p.tied()) gemm_nt(sc.lnf, p.wte, logits); else gemm_nn(sc.lnf, p.lm_head, logits); } // --------------------------------------------------------------------------- // Сэмплинг. В 0.0.4 здесь было три бага: // 1) repeat_penalty проставлялся в lp, а следом lp полностью перезаписывался // логитами → штраф не работал никогда; // 2) top-k: порог брался по v[top_k] (оставлял k+1 токен), а при V <= top_k // ветка молча отключалась; // 3) top-p: отброшенные токены обнулялись, остальные делились на s2, а выборка // шла по r = uniform() * sum со СТАРОЙ суммой → распределение было неверным; // плюс std::find внутри цикла по V давал O(V²) на каждый токен. // --------------------------------------------------------------------------- int sample(const Tensor& logits, const GenConfig& gc, Rng& rng, const std::vector& history) { const int V = logits.C(); if (V <= 0) return 0; // Буферы переиспользуются между вызовами — на длинной генерации это // экономит по 3-4 аллокации на токен. static std::vector lp; static std::vector keep; static std::vector> ord; lp.assign((size_t)V, 0.0f); keep.assign((size_t)V, 1); ord.resize((size_t)V); const float* lg = logits.ptr(); for (int j = 0; j < V; ++j) lp[j] = lg[j]; // --- repeat penalty --- const float rp = gc.repeat_penalty; if (std::fabs(rp - 1.0f) > 1e-6f) { static std::vector seen; seen.assign((size_t)V, 0); // штраф имеет смысл только за недавнюю историю, иначе O(n) на каждый токен const size_t from = history.size() > 512 ? history.size() - 512 : 0; for (size_t i = from; i < history.size(); ++i) { const int id = history[i]; if (id < 0 || id >= V || seen[id]) continue; seen[id] = 1; lp[id] -= (rp > 1.0f) ? (rp - 1.0f) : (1.0f - 1.0f / std::max(rp, 1e-6f)); } } // --- жадный режим --- if (gc.temperature <= 0.0f) { int best = 0; float bv = -1e30f; for (int j = 0; j < V; ++j) if (lp[j] > bv) { bv = lp[j]; best = j; } return best; } for (int j = 0; j < V; ++j) lp[j] /= gc.temperature; // --- top-k --- if (gc.top_k > 0 && V > 1) { const int k = std::min(gc.top_k, V); // было: молча выкл при V <= top_k for (int j = 0; j < V; ++j) ord[j] = {lp[j], j}; std::partial_sort(ord.begin(), ord.begin() + k, ord.end(), [](const std::pair& a, const std::pair& b) { return a.first > b.first; }); // (здесь раньше лежала cut = ord[k-1].first — после перехода на // частичную сортировку порог не нужен, отсечка идёт по keep[]) keep.assign((size_t)V, 0); for (int i = 0; i < k; ++i) keep[ord[i].second] = 1; for (int j = 0; j < V; ++j) if (!keep[j]) lp[j] = -1e30f; } // --- softmax --- float mx = -1e30f; for (int j = 0; j < V; ++j) mx = std::max(mx, lp[j]); if (!std::isfinite(mx)) return 0; double sum = 0.0; for (int j = 0; j < V; ++j) { lp[j] = std::exp(lp[j] - mx); sum += lp[j]; } if (!(sum > 0.0) || !std::isfinite(sum)) return 0; // --- top-p (nucleus) --- if (gc.top_p > 0.0f && gc.top_p < 1.0f) { for (int j = 0; j < V; ++j) ord[j] = {lp[j] / (float)sum, j}; std::partial_sort(ord.begin(), ord.end(), ord.end(), [](const std::pair& a, const std::pair& b) { return a.first > b.first; }); keep.assign((size_t)V, 0); double acc = 0.0; for (int j = 0; j < V; ++j) { keep[ord[j].second] = 1; acc += ord[j].first; if (acc >= (double)gc.top_p) break; } sum = 0.0; for (int j = 0; j < V; ++j) { if (keep[j]) sum += lp[j]; else lp[j] = 0.0f; } if (!(sum > 0.0)) return 0; } // --- выборка: lp уже нормированы на sum --- double r = rng.uniform() * sum; double a = 0.0; for (int j = 0; j < V; ++j) { a += lp[j]; if (r <= a) return j; } return V - 1; } // Печатать ли пробел после токена (слово vs одиночный символ). inline bool needs_space_after(const Tokenizer& tok, int id) { return id >= Tokenizer::n_special && id < tok.size() && tok.id2tok[id].size() > 1; } } // namespace gen_impl // =========================================================================== // generate_from — ядро: генерация продолжения из готовой истории токенов // =========================================================================== std::string generate_from(const Params& p, const Tokenizer& tok, std::vector history, const GenConfig& gc, GenOutStats* st, TokenCallback on_token) { using namespace gen_impl; const Config& c = p.cfg; GenOutStats dummy; GenOutStats& S = st ? *st : dummy; S = GenOutStats(); const int block = std::max(2, c.block_size); // стартовая история не должна занимать весь контекст: нужен хотя бы 1 слот под генерацию if ((int)history.size() > block - 1) history.resize((size_t)block - 1); if (history.empty()) history.push_back(tok.bos); S.prompt_tokens = (int)history.size(); KvCache kv; kv.init(c.n_layer, block, c.n_head, c.head_dim()); std::vector cs, sn; rope_tables(block, c.head_dim(), c.rope_base, cs, sn); Rng rng(gc.seed >= 0 ? (uint64_t)gc.seed : (uint64_t)std::chrono::steady_clock::now().time_since_epoch().count()); FwdScratch sc; Tensor logits; const auto t_start = std::chrono::steady_clock::now(); // порог слайда: держим 1 слот в запасе, иначе pos дорастёт до block и KvCache::off // вылетит за границы (в 0.0.4 проверка стояла на >= block_size) const int slide_at = block - 1; // --- prefill: прогоняем ВЕСЬ промпт, сэмплинг не делаем --- for (size_t i = 0; i < history.size(); ++i) { forward_token(p, kv, sc, history[i], kv.len, cs, sn, logits); kv.len++; } S.prefill_ns = std::chrono::duration_cast( std::chrono::steady_clock::now() - t_start).count(); const auto t_gen = std::chrono::steady_clock::now(); int feed = -1; // -1 → на первой итерации кормим последний токен промпта for (int n = 0; n < gc.max_new_tokens; ++n) { if (kv.len >= slide_at) { // --- переполнение контекста: оставляем хвост и пере-префиллим --- // (в 0.0.4 здесь было ids[i] = ids[ids.size() - keep + i] — чтение за // границей вектора при i >= keep, плюс kv.len расходился с ids.size()) const int keep = std::max(1, block / 2); if ((int)history.size() > keep) history.erase(history.begin(), history.end() - keep); kv.reset(); for (size_t i = 0; i < history.size(); ++i) { forward_token(p, kv, sc, history[i], kv.len, cs, sn, logits); kv.len++; } feed = -1; } if (gc.cancel && gc.cancel->load()) { S.stop_reason = "cancelled"; break; } const int tok_in = (feed < 0) ? history.back() : feed; forward_token(p, kv, sc, tok_in, kv.len, cs, sn, logits); kv.len++; const int next = sample(logits, gc, rng, history); S.tokens.push_back(next); feed = next; // gc.stop_token объявлялся в GenConfig, но нигде не читался: остановить // генерацию на произвольном токене было нельзя (bench из-за этого не мог // замерить скорость — модель обрывала вывод на первом же ). const int stop = (gc.stop_token >= 0) ? gc.stop_token : tok.eos; if (next == stop) { S.stop_reason = "eos"; break; } // страховка: без маски loss у маркера ненулевая вероятность, // и модель может начать отвечать сама за себя if (tok.has_chat_tokens() && next == tok.user) { S.stop_reason = "role"; break; } history.push_back(next); if (on_token) on_token(next, tok.decode_one(next)); } if (S.stop_reason.empty()) S.stop_reason = ((int)S.tokens.size() >= gc.max_new_tokens) ? "length" : "unknown"; S.gen_ns = std::chrono::duration_cast( std::chrono::steady_clock::now() - t_gen).count(); if (S.gen_ns < 0) S.gen_ns = 0; // history обрезана слайдами — наружу отдаём только промпт + сгенерированное history.resize((size_t)S.prompt_tokens); history.insert(history.end(), S.tokens.begin(), S.tokens.end()); std::string out; out.reserve(S.tokens.size() * 4); for (int id : S.tokens) { out += tok.decode_one(id); if (needs_space_after(tok, id)) out += " "; } return out; } // =========================================================================== // chat_turn — один диалоговый ход // =========================================================================== std::string chat_turn(const Params& p, const Tokenizer& tok, std::vector& history, const std::string& user_text, const GenConfig& gc, GenOutStats* st, TokenCallback on_token) { if (!tok.has_chat_tokens() || tok.user < 0 || tok.asst < 0) { if (st) { st->stop_reason = "error"; } return "[ошибка] словарь модели не содержит / — чат невозможен. " "Пересоздай модель командой new."; } if (history.empty()) history.push_back(tok.bos); // --- подставляем маркеры и реплику пользователя --- history.push_back(tok.user); std::vector u = tok.encode(user_text, /*add_bos=*/false); // encode() всегда дописывает в конец (checkpoint.cpp) — срезаем, // иначе окажется внутри реплики и генерация оборвётся на первом слове while (!u.empty() && u.back() == tok.eos) u.pop_back(); while (!u.empty() && u.front() == tok.bos) u.erase(u.begin()); history.insert(history.end(), u.begin(), u.end()); history.push_back(tok.asst); // --- генерируем ответ --- const std::string answer = generate_from(p, tok, history, gc, st, on_token); // --- фиксируем ход в истории, чтобы следующий вызов его видел --- if (st) history.insert(history.end(), st->tokens.begin(), st->tokens.end()); history.push_back(tok.eos); return answer; } // =========================================================================== // Обратная совместимость: старый API поверх нового // =========================================================================== std::string generate(const Params& p, const Tokenizer& tok, const std::string& prompt, const GenConfig& gc, std::vector* out_ids) { std::vector history = tok.encode(prompt, true); TokenCallback cb; if (gc.stream) { cb = [&tok](int id, const std::string& piece) { std::fputs(piece.c_str(), stdout); if (gen_impl::needs_space_after(tok, id)) std::fputc(' ', stdout); std::fflush(stdout); }; } GenOutStats st; const std::string text = tok.decode(history, true) + generate_from(p, tok, history, gc, &st, cb); if (gc.stream) { std::fputc('\n', stdout); std::fflush(stdout); } // generate_from() принимает history ПО ЗНАЧЕНИЮ, поэтому локальный history // остаётся равным промпту, а сгенерированное лежит в st.tokens: // out_ids = [токены промпта][сгенерированные токены]. if (out_ids) { *out_ids = history; out_ids->insert(out_ids->end(), st.tokens.begin(), st.tokens.end()); } return text; } std::vector generate_batch(const Params& p, const Tokenizer& tok, const std::vector& prompts, const GenConfig& gc) { std::vector out; out.reserve(prompts.size()); for (const std::string& s : prompts) { GenConfig g = gc; g.stream = false; // в батче стрим только мешает out.push_back(generate(p, tok, s, g, nullptr)); } return out; } } // namespace xt