File size: 19,144 Bytes
68888be | 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 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 | // hkimi run | chat | tokenize
#include <algorithm>
#include <cstdio>
#include <filesystem>
#include <fstream>
#include "cli/args.h"
#include "cli/commands.h"
#include "cli/engine.h"
#include "common/base.h"
#include "common/console.h"
#include "common/json.h"
#include "drafter/dspark.h"
#include "format/store_io.h"
#include "io/os_info.h"
#include "loop/day_loop.h"
#include "loop/draft_loop.h"
#include "tokenizer/chat.h"
#include "tokenizer/tokenizer.h"
namespace hk {
namespace {
#define HK_DAY_OPTIONS "max-new", "max-rounds", "draft-len", "drafter", "draft-cost"
DayOptions day_options(const Args& a) {
DayOptions o;
o.max_new = (int)a.num("max-new", o.max_new);
o.max_rounds = (int)a.num("max-rounds", o.max_rounds);
o.draft_len = (int)a.num("draft-len", o.draft_len);
o.extra_cost = a.real("draft-cost", 0.0);
HK_CHECK(o.extra_cost >= 0.0 && o.extra_cost <= 1.0, "--draft-cost is a share of one sweep, between 0 and 1");
HK_CHECK(a.has("drafter") || !a.has("draft-cost"), "--draft-cost goes with --drafter DIR");
HK_CHECK(o.max_new > 0, "--max-new must be positive");
return o;
}
std::vector<int32_t> ids_from(const Args& a, const char* key, const char* file_key) {
if (a.has(file_key)) return parse_int_list(read_text_file(a.str(file_key)));
return parse_int_list(a.str(key));
}
void check_ids(const std::vector<int32_t>& ids, int vocab) {
for (int32_t t : ids) HK_CHECK(t >= 0 && t < vocab, "token id %d is outside the vocabulary (0..%d)", t, vocab - 1);
}
std::string join_ids(const std::vector<int32_t>& ids, const char* sep) {
std::string s;
for (size_t i = 0; i < ids.size(); ++i) s += (i ? sep : "") + std::to_string(ids[i]);
return s;
}
// line ends and tabs shown as escapes
std::string one_line(const std::string& s) {
std::string o;
for (char c : s) {
if (c == '\n') o += "\\n";
else if (c == '\r') o += "\\r";
else if (c == '\t') o += "\\t";
else o += c;
}
return o;
}
// the drafter and its conversation (--drafter DIR)
struct Session {
std::unique_ptr<DSpark> drafter;
std::unique_ptr<DraftSession> draft;
void open(const Args& a, Engine& eng, bool announce) {
const double t0 = now_sec();
drafter.reset(new DSpark(a.str("drafter"), eng.store, eng.reader->store_io(), *eng.bk, eng.reader->lm_head()));
draft.reset(new DraftSession(*eng.reader, *drafter));
if (announce) printf("drafter: %s (loaded in %.1f s)\n", drafter->describe().c_str(), now_sec() - t0);
}
DayResult generate(const std::vector<int32_t>& prompt, const DayOptions& opt, const DayCallbacks& cb) {
return draft->generate(prompt, opt, cb);
}
const std::vector<int32_t>& context() const { return draft->context(); }
void reset() { draft->reset(); }
};
std::unique_ptr<Tokenizer> load_tokenizer(const Store& store) {
std::unique_ptr<Tokenizer> tok;
if (!Tokenizer::available(store.dir())) return tok;
tok.reset(new Tokenizer(Tokenizer::load(store.dir(), store.config().vocab)));
if (!tok->pattern_warning().empty()) HK_WARN("%s", tok->pattern_warning().c_str());
if (tok->vocab_size() > store.config().vocab)
HK_WARN("the tokenizer knows %d tokens, the model %d: are these the tokenizer files of this checkpoint?", tok->vocab_size(),
store.config().vocab);
return tok;
}
std::string stats_line(const DayResult& r) {
int drafted = 0, kept = 0;
for (const RoundInfo& ri : r.rounds) {
drafted += ri.drafted;
kept += ri.accepted;
}
return strfmt("[%zu tokens in %.1f s, %.1f s per token: %zu sweep%s by real Kimi (%.1f s, %s read), %.2f tokens per sweep, "
"%d of %d drafted tokens kept, drafting %.1f s]",
r.tokens.size(), r.seconds, r.tokens.empty() ? 0.0 : r.seconds / (double)r.tokens.size(), r.rounds.size(),
r.rounds.size() == 1 ? "" : "s", r.sweep_seconds, human_bytes((double)r.sweep_bytes).c_str(),
r.rounds.empty() ? 0.0 : (double)r.tokens.size() / (double)r.rounds.size(), kept, drafted, r.draft_seconds);
}
// Prints tokens as text while they arrive and keeps the answer for the chat history.
struct Streamer {
const Tokenizer& tok;
ReplyParser parser;
ReplyParser::Kind last = ReplyParser::None;
bool print;
std::string answer;
Streamer(const Tokenizer& t, ChatStyle style, bool think, bool print_) : tok(t), parser(t, style, think), print(print_) {}
void emit(const std::string& text, ReplyParser::Kind kind) {
if (text.empty()) return;
if (kind == ReplyParser::Answer) answer += text;
if (!print) return;
if (kind != last) {
if (kind == ReplyParser::Thinking) console_write("(thinking) ");
else if (last == ReplyParser::Thinking) console_write("\n(answer) ");
last = kind;
}
console_write(text);
}
void push(const int32_t* ids, int n) {
for (int i = 0; i < n; ++i) {
ReplyParser::Kind kind;
std::string text = parser.push(ids[i], &kind);
emit(text, kind);
}
}
void finish() { emit(parser.flush(), last == ReplyParser::None ? ReplyParser::Answer : last); }
};
} // namespace
// ---- run -------------------------------------------------------------------------------
int cmd_run(const Args& a) {
a.allow({HK_ENGINE_OPTIONS, HK_DAY_OPTIONS, "prompt", "prompt-file", "system", "tokens", "tokens-file", "stop", "think", "raw", "json",
"reader-only", "quiet", "dump-drafts", "then"});
const bool json = a.flag("json"), quiet = a.flag("quiet"), drafted = a.has("drafter");
HK_CHECK(!(a.flag("reader-only") && drafted), "--reader-only is real Kimi alone: it does not go with --drafter");
HK_CHECK(drafted || !(a.has("dump-drafts") || a.has("then")), "--dump-drafts and --then go with --drafter DIR");
const bool reader_only = !drafted; // without a drafter real Kimi writes alone, one sweep per token
Engine eng;
eng.keep_head = drafted;
eng.open(a);
const int vocab = eng.store.config().vocab;
std::unique_ptr<Tokenizer> tok = load_tokenizer(eng.store);
DayOptions opt = day_options(a);
std::vector<int32_t> prompt;
const bool text_mode = a.has("prompt") || a.has("prompt-file");
const bool think = a.flag("think");
ChatStyle style = ChatStyle::Raw;
if (text_mode) {
HK_CHECK(tok != nullptr, "this store has no tokenizer files (tokenizer/tiktoken.model); pass token ids with --tokens instead");
std::string text = a.has("prompt-file") ? read_text_file(a.str("prompt-file")) : a.str("prompt");
if (a.flag("raw")) {
prompt = tok->encode(text);
} else {
ChatFormat chat(*tok);
std::vector<ChatMessage> msgs;
if (a.has("system")) msgs.push_back({"system", a.str("system")});
msgs.push_back({"user", text});
prompt = chat.render(msgs, think);
opt.stop_ids = chat.stop_ids();
style = chat.style();
}
} else {
prompt = ids_from(a, "tokens", "tokens-file");
}
for (int32_t s : parse_int_list(a.str("stop"))) opt.stop_ids.push_back(s);
HK_CHECK(!prompt.empty(), "give a prompt: --prompt TEXT, --prompt-file FILE, --tokens 1,2,3 or --tokens-file FILE");
check_ids(prompt, vocab);
if (reader_only) {
// real Kimi alone, one sweep per token
const double t0 = now_sec();
std::vector<int32_t> out = reader_greedy(*eng.reader, prompt, opt.max_new, opt.stop_ids);
if (json) {
Json j = Json::object();
Json ids = Json::array();
for (int32_t t : out) ids.push(Json((int64_t)t));
j.set("tokens", std::move(ids));
j.set("seconds", now_sec() - t0);
j.set("sweeps", Json((int64_t)out.size()));
j.set("device_peak_bytes", Json(eng.bk->mem_peak()));
j.set("trunk_ram_bytes", Json(eng.reader->trunk_kept_bytes()));
j.set("ram_peak_bytes", Json(process_ram_peak_bytes()));
j.set("trunk_ahead_bytes", Json(eng.reader->store_io().bytes_ahead()));
if (tok) j.set("text", tok->decode(out));
console_write(j.dump() + "\n");
} else {
printf("tokens: %s\n", join_ids(out, " ").c_str());
if (tok) console_write("text : " + one_line(tok->decode(out)) + "\n");
if (!quiet) printf("[%zu tokens in %.1f s, one sweep each]\n", out.size(), now_sec() - t0);
}
return 0;
}
Session session;
session.open(a, eng, /*announce=*/!json && !quiet);
std::vector<DraftSession::Drafted> drafts;
if (a.has("dump-drafts")) session.draft->record = &drafts;
std::unique_ptr<Streamer> stream;
DayCallbacks cb;
if (text_mode) {
stream.reset(new Streamer(*tok, style, think, /*print=*/!json));
cb.on_approved = [&](const int32_t* ids, int n) { stream->push(ids, n); };
}
DayResult res = session.generate(prompt, opt, cb);
if (stream) stream->finish();
// --then 1,2,3 (tests): appended as a second turn; the conversation goes on from
// where the first answer left it
const std::vector<int32_t> then_ids = parse_int_list(a.str("then"));
check_ids(then_ids, vocab);
DayResult res2;
if (!then_ids.empty()) res2 = session.generate(then_ids, opt, DayCallbacks());
if (a.has("dump-drafts")) {
// one line per round: anchor position, the draft, the drafter's confidence, what was kept
std::string lines;
for (const DraftSession::Drafted& d : drafts) {
Json j = Json::object(), ids = Json::array(), conf = Json::array();
for (int32_t t : d.block.tokens) ids.push(Json((int64_t)t));
for (float cf : d.block.conf) conf.push(Json((double)cf));
j.set("anchor", Json((int64_t)d.anchor_pos));
j.set("tokens", std::move(ids));
j.set("confidence", std::move(conf));
j.set("checked", Json((int64_t)d.checked));
j.set("kept", Json((int64_t)d.kept));
lines += j.dump() + "\n";
}
std::ofstream f(std::filesystem::u8path(a.str("dump-drafts")), std::ios::binary | std::ios::trunc);
f.write(lines.data(), (std::streamsize)lines.size());
HK_CHECK(f.good(), "cannot write %s", a.str("dump-drafts").c_str());
}
if (json) {
Json j = Json::object();
Json ids = Json::array();
for (int32_t t : res.tokens) ids.push(Json((int64_t)t));
j.set("tokens", std::move(ids));
j.set("fixes", res.fixes);
j.set("sweeps", Json((int64_t)res.rounds.size()));
j.set("stopped", res.stopped);
j.set("seconds", res.seconds);
j.set("draft_seconds", res.draft_seconds);
j.set("sweep_seconds", res.sweep_seconds);
j.set("sweep_bytes", Json(res.sweep_bytes));
// device memory peak (0 on the CPU), trunk kept in RAM, RAM peak of the process, trunk copied ahead
j.set("device_peak_bytes", Json(eng.bk->mem_peak()));
j.set("trunk_ram_bytes", Json(eng.reader ? eng.reader->trunk_kept_bytes() : (int64_t)0));
j.set("ram_peak_bytes", Json(process_ram_peak_bytes()));
j.set("trunk_ahead_bytes", Json(eng.reader ? eng.reader->store_io().bytes_ahead() : (int64_t)0));
if (drafted) {
j.set("drafted", Json(session.draft->drafted()));
j.set("kept", Json(session.draft->accepted()));
// the first sweep reads the whole prompt: a cost per answer, not per token
j.set("prompt_seconds", res.rounds.empty() ? 0.0 : res.rounds[0].sweep_seconds);
}
if (!then_ids.empty()) {
Json more = Json::array();
for (int32_t t : res2.tokens) more.push(Json((int64_t)t));
j.set("then_tokens", std::move(more));
j.set("then_sweeps", Json((int64_t)res2.rounds.size()));
}
if (tok) j.set("text", stream ? stream->answer : tok->decode(res.tokens));
console_write(j.dump() + "\n");
return 0;
}
if (text_mode) {
console_write("\n");
} else {
printf("tokens: %s\n", join_ids(res.tokens, " ").c_str());
if (tok) console_write("text : " + one_line(tok->decode(res.tokens)) + "\n");
}
if (!then_ids.empty()) printf("then : %s\n", join_ids(res2.tokens, " ").c_str());
if (!quiet) {
printf("%s\n", stats_line(res).c_str());
if (!res.stopped && !opt.stop_ids.empty()) printf("(stopped at --max-new %d before the model ended its turn)\n", opt.max_new);
}
return 0;
}
// ---- chat ------------------------------------------------------------------------------
int cmd_chat(const Args& a) {
a.allow({HK_ENGINE_OPTIONS, HK_DAY_OPTIONS, "system", "think", "show-draft"});
HK_CHECK(a.has("drafter"), "chat writes with the drafter: give --drafter DIR (real Kimi alone, one sweep per token: hkimi run)");
Engine eng;
eng.keep_head = true;
eng.open(a);
std::unique_ptr<Tokenizer> tok = load_tokenizer(eng.store);
HK_CHECK(tok != nullptr, "this store has no tokenizer files (tokenizer/tiktoken.model). Convert the checkpoint again with its "
"tokenizer files next to the weights, or use `hkimi run --tokens`.");
ChatFormat chat(*tok);
DayOptions opt = day_options(a);
opt.stop_ids = chat.stop_ids();
const bool think = a.flag("think"), show_draft = a.flag("show-draft");
std::vector<ChatMessage> history;
if (a.has("system")) history.push_back({"system", a.str("system")});
const size_t base_history = history.size();
bool clean = true; // the conversation in the session ends with a finished turn (or is empty)
int64_t total_tokens = 0, total_sweeps = 0;
double total_seconds = 0;
printf("%s\n", eng.store.config().summary().c_str());
printf("backend %s (%s), chat format: %s, every token is real Kimi's own\n", eng.bk->name(), eng.bk->device_name().c_str(),
chat.style_name());
Session session;
session.open(a, eng, /*announce=*/true);
printf("commands: /reset /stats /exit\n");
for (;;) {
console_write("\nyou> ");
std::string line;
if (!console_read_line(line)) break;
if (!stdin_is_terminal()) console_write(line + "\n"); // piped input: echo it so the transcript reads well
while (!line.empty() && (line.back() == ' ' || line.back() == '\t')) line.pop_back();
if (line.empty()) continue;
if (line == "/exit" || line == "/quit") break;
if (line == "/reset") {
session.reset();
history.resize(base_history);
clean = true;
printf("(conversation cleared)\n");
continue;
}
if (line == "/stats") {
printf("%lld tokens in %lld sweeps (%.2f per sweep), %.1f s, %.1f s per token; %lld of %lld drafted tokens kept\n",
(long long)total_tokens, (long long)total_sweeps, total_sweeps ? (double)total_tokens / (double)total_sweeps : 0.0,
total_seconds, total_tokens ? total_seconds / (double)total_tokens : 0.0, (long long)session.draft->accepted(),
(long long)session.draft->drafted());
continue;
}
if (line[0] == '/') {
printf("unknown command %s (commands: /reset /stats /exit)\n", line.c_str());
continue;
}
// Only the new turn is rendered, the rest is already in the session. If the last
// answer was cut off (no end of turn) the markup is unbalanced: rebuild from the text.
std::vector<ChatMessage> turn;
if (!clean) session.reset();
if (session.context().empty()) turn = history;
turn.push_back({"user", line});
std::vector<int32_t> prompt = chat.render(turn, think);
Streamer stream(*tok, chat.style(), think, /*print=*/!show_draft);
DayCallbacks cb;
std::vector<int32_t> last_draft;
int round = 0;
cb.on_draft = [&](const int32_t* ids, int n) {
last_draft.assign(ids, ids + n);
if (show_draft) console_write(strfmt(" draft %d: ", ++round) + one_line(tok->decode(last_draft)) + "\n");
};
cb.on_approved = [&](const int32_t* ids, int n) {
stream.push(ids, n);
if (!show_draft) return;
int same = 0;
while (same < n && same < (int)last_draft.size() && ids[same] == last_draft[(size_t)same]) ++same;
if (same < n && same < (int)last_draft.size())
console_write(strfmt(" real Kimi kept %d of %zu tokens and wrote \"", same, last_draft.size()) + one_line(tok->token(ids[same])) +
"\" instead of \"" + one_line(tok->token(last_draft[(size_t)same])) + "\"\n");
else
console_write(strfmt(" real Kimi kept all %d tokens\n", same));
};
if (!show_draft) console_write("kimi> ");
DayResult res = session.generate(prompt, opt, cb);
stream.finish();
if (show_draft) console_write("kimi> " + stream.answer);
console_write("\n");
printf("%s\n", stats_line(res).c_str());
history.push_back({"user", line});
history.push_back({"assistant", stream.answer});
clean = res.stopped || chat.style() == ChatStyle::Raw;
if (!res.stopped && chat.style() != ChatStyle::Raw) printf("(cut at --max-new %d)\n", opt.max_new);
total_tokens += (int64_t)res.tokens.size();
total_sweeps += (int64_t)res.rounds.size();
total_seconds += res.seconds;
}
return 0;
}
// ---- tokenize --------------------------------------------------------------------------
int cmd_tokenize(const Args& a) {
a.allow({"text", "file", "ids", "ids-file", "pieces", "chat", "think"});
Tokenizer tok = Tokenizer::load(a.need_pos(0, "a store, or a directory with tiktoken.model"));
if (!tok.pattern_warning().empty()) HK_WARN("%s", tok.pattern_warning().c_str());
if (a.has("ids") || a.has("ids-file")) {
std::vector<int32_t> ids = ids_from(a, "ids", "ids-file");
check_ids(ids, tok.vocab_size());
console_write(tok.decode(ids) + "\n");
return 0;
}
HK_CHECK(a.has("text") || a.has("file"), "give --text TEXT or --file FILE to encode, or --ids 1,2,3 to decode");
std::string text = a.has("file") ? read_text_file(a.str("file")) : a.str("text");
if (a.flag("pieces")) {
// the pre-tokenizer's cut points, as byte lengths
std::string out;
for (const std::string& p : tok.pieces(text)) out += (out.empty() ? "" : ",") + std::to_string(p.size());
printf("%s\n", out.c_str());
return 0;
}
std::vector<int32_t> ids;
if (a.flag("chat")) ids = ChatFormat(tok).render({{"user", text}}, a.flag("think"));
else ids = tok.encode(text);
printf("%s\n", join_ids(ids, ",").c_str());
return 0;
}
} // namespace hk
|