@@ -451,6 +451,9 @@ llama_context::llama_context(
451451}
452452
453453llama_context::~llama_context () {
454+ // wait for any pending asynchronous copies into the output buffers before they are freed
455+ synchronize ();
456+
454457 if (!model.hparams .no_alloc ) {
455458 for (size_t i = 0 ; i < backend_ptrs.size (); ++i) {
456459 ggml_backend_t backend = backend_ptrs[i];
@@ -1386,13 +1389,17 @@ int llama_context::encode(const llama_batch & batch_inp) {
13861389 // micro-batching is not possible for non-causal encoding, so we process the batch in a single shot
13871390 GGML_ASSERT (cparams.n_ubatch >= n_tokens && " encoder requires n_ubatch >= n_tokens" );
13881391
1392+ // TODO: this clear of the buffer can easily be forgotten - need something better
1393+ // sync first so any in-flight async copies into embd_seq complete before it is freed
1394+ if (!embd_seq.empty ()) {
1395+ synchronize ();
1396+ }
1397+ embd_seq.clear ();
1398+
13891399 if (t_compute_start_us == 0 ) {
13901400 t_compute_start_us = ggml_time_us ();
13911401 }
13921402
1393- // TODO: this clear of the buffer can easily be forgotten - need something better
1394- embd_seq.clear ();
1395-
13961403 sched_reserve ();
13971404
13981405 n_queued_tokens += n_tokens;
@@ -1731,13 +1738,18 @@ int llama_context::decode(const llama_batch & batch_inp) {
17311738
17321739 GGML_ASSERT ((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && " non-causal attention requires n_ubatch >= n_tokens" );
17331740
1741+ // TODO: this clear of the buffer can easily be forgotten - need something better
1742+ // sync first so any in-flight async copies into embd_seq complete before it is freed
1743+ if (!embd_seq.empty ()) {
1744+ synchronize ();
1745+ }
1746+ embd_seq.clear ();
1747+
17341748 if (t_compute_start_us == 0 ) {
17351749 t_compute_start_us = ggml_time_us ();
17361750 }
17371751 n_queued_tokens += n_tokens_all;
17381752
1739- // TODO: this clear of the buffer can easily be forgotten - need something better
1740- embd_seq.clear ();
17411753 output_swaps.clear ();
17421754
17431755 sched_reserve ();
0 commit comments