0.3.1
This commit is contained in:
1 parent
588f30c327
commit
5474c39849
125 files changed
+734458
-589
No files matched your search
@@ -215,6 +215,9 @@ public:
|
||||
std::shared_ptr<TrainState> state = std::make_shared<TrainState>();
|
||||
std::thread worker;
|
||||
std::future<void> done_fut_;
|
||||
// Отдельный замок для worker/done_fut_: wait() и train_async() могут
|
||||
// прийти из разных python-потоков, а join() одного std::thread дважды — UB.
|
||||
std::mutex worker_mtx;
|
||||
py::object on_tick_ = py::none(), on_note_ = py::none();
|
||||
|
||||
// сериализация тяжёлых операций над одной моделью
|
||||
@@ -303,39 +306,53 @@ public:
|
||||
// self (shared_ptr) в замыкании — keep-alive: модель переживёт потерю
|
||||
// python-ссылки, пока обучение идёт.
|
||||
// ------------------------------------------------------------------
|
||||
void start_worker(std::function<TrainStats()> job, const std::string& out_path) {
|
||||
void start_worker(std::function<TrainStats()> job, const std::string& out_path,
|
||||
const char* kind, int total_steps) {
|
||||
// Сначала подбираем завершённый прошлый поток и только ПОТОМ сбрасываем
|
||||
// TrainState. Иначе begin() сбрасывал фазу в Running до проверки, и
|
||||
// повторный train_async после завершения падал с «уже запущено»,
|
||||
// оставляя статус Running навсегда (без работающего потока).
|
||||
std::lock_guard<std::mutex> wlk(worker_mtx);
|
||||
if (worker.joinable()) {
|
||||
if (state->phase.load() != TrainState::Running) {
|
||||
if (done_fut_.valid()) done_fut_.wait();
|
||||
worker.join(); // прошлый прогон закончился — подбираем поток
|
||||
} else {
|
||||
if (state->phase.load() == TrainState::Running)
|
||||
throwx("обучение уже запущено: дождитесь model.wait() или вызовите model.stop()");
|
||||
}
|
||||
// Фаза уже не Running; поток мог ещё не выставить promise —
|
||||
// дожидаемся его, чтобы join() не гонялся с finish_ok().
|
||||
if (done_fut_.valid()) done_fut_.wait();
|
||||
worker.join();
|
||||
}
|
||||
state->begin(kind, total_steps);
|
||||
auto self = shared_from_this();
|
||||
auto st = state;
|
||||
auto promise = std::make_shared<std::promise<void>>();
|
||||
done_fut_ = promise->get_future();
|
||||
cancel_ = false;
|
||||
worker = std::thread([self, job, st, out_path, promise] {
|
||||
// Поток создан из-под GIL, но сам GIL НЕ держит (std::thread).
|
||||
TrainStats stats;
|
||||
std::string err;
|
||||
try {
|
||||
stats = job();
|
||||
if (!stats.error.empty() && stats.step == 0) err = stats.error;
|
||||
} catch (const std::exception& e) {
|
||||
err = e.what();
|
||||
} catch (...) {
|
||||
err = "неизвестная ошибка";
|
||||
}
|
||||
if (!err.empty()) st->finish_fail(err, stats);
|
||||
else st->finish_ok(stats, out_path);
|
||||
promise->set_value();
|
||||
});
|
||||
try {
|
||||
worker = std::thread([self, job, st, out_path, promise] {
|
||||
// Поток создан из-под GIL, но сам GIL НЕ держит (std::thread).
|
||||
TrainStats stats;
|
||||
std::string err;
|
||||
try {
|
||||
stats = job();
|
||||
if (!stats.error.empty() && stats.step == 0) err = stats.error;
|
||||
} catch (const std::exception& e) {
|
||||
err = e.what();
|
||||
} catch (...) {
|
||||
err = "неизвестная ошибка";
|
||||
}
|
||||
if (!err.empty()) st->finish_fail(err, stats);
|
||||
else st->finish_ok(stats, out_path);
|
||||
promise->set_value();
|
||||
});
|
||||
} catch (const std::exception& e) {
|
||||
state->finish_fail(std::string("не удалось запустить поток: ") + e.what(),
|
||||
TrainStats{});
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
void join_worker(double timeout_sec) {
|
||||
std::lock_guard<std::mutex> wlk(worker_mtx);
|
||||
if (!worker.joinable()) return;
|
||||
if (timeout_sec > 0) {
|
||||
if (done_fut_.valid() &&
|
||||
@@ -1305,16 +1322,24 @@ PYBIND11_MODULE(xenith_engine, m) {
|
||||
// колбэки готовятся ПОД GIL (копии py::object), прогон — БЕЗ GIL
|
||||
m.on_tick_ = on_tick; m.on_note_ = on_note;
|
||||
m.state->begin("train", steps);
|
||||
ProgressFn tick = m.make_tick_fn();
|
||||
NoteFn note = m.make_note_fn();
|
||||
TrainStats st;
|
||||
{
|
||||
py::gil_scoped_release rel;
|
||||
st = run_train_sync(m, a, tick, note);
|
||||
try {
|
||||
ProgressFn tick = m.make_tick_fn();
|
||||
NoteFn note = m.make_note_fn();
|
||||
TrainStats st;
|
||||
{
|
||||
py::gil_scoped_release rel;
|
||||
st = run_train_sync(m, a, tick, note);
|
||||
}
|
||||
m.state->finish_ok(st, out_path);
|
||||
if (st.cancelled) m.state->phase = TrainState::Cancelled;
|
||||
return st;
|
||||
} catch (const std::exception& e) {
|
||||
m.state->finish_fail(e.what(), TrainStats{});
|
||||
throw;
|
||||
} catch (...) {
|
||||
m.state->finish_fail("неизвестная ошибка", TrainStats{});
|
||||
throw;
|
||||
}
|
||||
m.state->finish_ok(st, out_path);
|
||||
if (st.cancelled) m.state->phase = TrainState::Cancelled;
|
||||
return st;
|
||||
},
|
||||
py::arg("corpus") = py::none(), py::arg("corpus_text") = py::none(),
|
||||
py::arg("out_path") = "", py::arg("steps") = 1000, py::arg("batch") = 8,
|
||||
@@ -1353,11 +1378,10 @@ PYBIND11_MODULE(xenith_engine, m) {
|
||||
a.threads = threads; a.resume = resume;
|
||||
|
||||
m.on_tick_ = on_tick; m.on_note_ = on_note;
|
||||
m.state->begin("train", steps);
|
||||
ProgressFn tick = m.make_tick_fn();
|
||||
NoteFn note = m.make_note_fn();
|
||||
m.start_worker([mp, a, tick, note] { return run_train_sync(*mp, a, tick, note); },
|
||||
out_path);
|
||||
out_path, "train", steps);
|
||||
return m.state;
|
||||
},
|
||||
py::arg("corpus") = py::none(), py::arg("corpus_text") = py::none(),
|
||||
@@ -1399,16 +1423,24 @@ PYBIND11_MODULE(xenith_engine, m) {
|
||||
|
||||
m.on_tick_ = on_tick; m.on_note_ = on_note;
|
||||
m.state->begin("finetune", steps);
|
||||
ProgressFn tick = m.make_tick_fn();
|
||||
NoteFn note = m.make_note_fn();
|
||||
TrainStats st;
|
||||
{
|
||||
py::gil_scoped_release rel;
|
||||
st = run_finetune_sync(m, a, tick, note);
|
||||
try {
|
||||
ProgressFn tick = m.make_tick_fn();
|
||||
NoteFn note = m.make_note_fn();
|
||||
TrainStats st;
|
||||
{
|
||||
py::gil_scoped_release rel;
|
||||
st = run_finetune_sync(m, a, tick, note);
|
||||
}
|
||||
m.state->finish_ok(st, out_path);
|
||||
if (st.cancelled) m.state->phase = TrainState::Cancelled;
|
||||
return st;
|
||||
} catch (const std::exception& e) {
|
||||
m.state->finish_fail(e.what(), TrainStats{});
|
||||
throw;
|
||||
} catch (...) {
|
||||
m.state->finish_fail("неизвестная ошибка", TrainStats{});
|
||||
throw;
|
||||
}
|
||||
m.state->finish_ok(st, out_path);
|
||||
if (st.cancelled) m.state->phase = TrainState::Cancelled;
|
||||
return st;
|
||||
},
|
||||
py::arg("data") = py::none(), py::arg("data_json") = py::none(),
|
||||
py::arg("ds_conf") = py::none(),
|
||||
@@ -1449,11 +1481,10 @@ PYBIND11_MODULE(xenith_engine, m) {
|
||||
a.label_smoothing = label_smoothing; a.threads = threads; a.resume = resume;
|
||||
|
||||
m.on_tick_ = on_tick; m.on_note_ = on_note;
|
||||
m.state->begin("finetune", steps);
|
||||
ProgressFn tick = m.make_tick_fn();
|
||||
NoteFn note = m.make_note_fn();
|
||||
m.start_worker([mp, a, tick, note] { return run_finetune_sync(*mp, a, tick, note); },
|
||||
out_path);
|
||||
out_path, "finetune", steps);
|
||||
return m.state;
|
||||
},
|
||||
py::arg("data") = py::none(), py::arg("data_json") = py::none(),
|
||||
|
||||
Reference in new issue
Block a user