Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions csrc/engine/compiler/paged_compiler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,10 @@ void PagedCompiler::compile() {
const auto *paged_config = dynamic_cast<const cache::PagedKVCacheConfig *>(
model_->get_cache_config());
if (paged_config != nullptr) {
// Release reusable staging blocks left by dense weight post-processing
// before graph capture; per-weight trims serialize too many device
// frees across TP ranks.
runtime_.trimMemory();
compiled_short_decode_b1_.reset();
compiled_map_decode_.clear();
block_tables_holder_.reset();
Expand Down
1 change: 1 addition & 0 deletions csrc/engine/rank_worker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -551,6 +551,7 @@ void RankWorker::thread_loop() {
runtime_ = infinilm::runtime::Runtime::create(rank_info_.device);
runtime_->activate();
forward_context_.runtime = runtime_.get();
forward_context_.pre_transpose = infinilm_config_->pre_transpose;
// Submission failure is terminal for this dedicated job-host process.
// This also opts every worker into the existing strict failure-drain paths.
runtime_->enableOwnerDrainFailStop();
Expand Down
9 changes: 0 additions & 9 deletions csrc/execution/graph/graph.cc
Original file line number Diff line number Diff line change
Expand Up @@ -194,15 +194,6 @@ void Graph::run() const {
}
const Segment *previous = nullptr;
for (const auto &segment : segments_) {
#ifdef USE_INFINIRT_GRAPH
if (!segment->capture_safe && previous != nullptr
&& previous->device_graph_ != nullptr
&& previous->device_graph_->exec != nullptr) {
// Host code may inspect the preceding device result. Later device
// work is submitted on the same stream, so it stays ordered.
previous->device_graph_->synchronize();
}
#endif
segment->run();
previous = segment.get();
}
Expand Down
3 changes: 3 additions & 0 deletions csrc/global_state/forward_context.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@ struct ForwardContext {
// Worker-owned; the context is used only while that worker is alive.
infinilm::runtime::Runtime *runtime{nullptr};
std::shared_ptr<const engine::nsa::Proof> nsa_owner;
// Dense NZ/packed layouts require contiguous FlashAttention prefill inputs.
// Keep the layout policy explicit instead of inferring it from the device.
bool pre_transpose{false};
AttentionMetadata attn_metadata;
MambaMetadata mamba_metadata;
MultiModalMetadata mm_metadata;
Expand Down
8 changes: 8 additions & 0 deletions csrc/layers/attention/backends/attention_layer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,14 @@ infinilm::runtime::Tensor AttentionLayer::forward(
auto &kv_cache = forward_context.kv_cache_vec[layer_idx_];
auto &runtime = *forward_context.runtime;

if (const auto *flash_impl =
std::get_if<std::shared_ptr<backends::FlashAttentionImpl>>(
&attn_backend_impl_)) {
return (*flash_impl)->forward(*this, query, key, value, kv_cache,
attn_metadata, runtime,
forward_context.pre_transpose);
}

return std::visit(
[&](auto &impl_ptr) -> infinilm::runtime::Tensor {
return impl_ptr->forward(*this, query, key, value, kv_cache,
Expand Down
23 changes: 17 additions & 6 deletions csrc/layers/attention/backends/flash_attn.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ infinilm::runtime::Tensor FlashAttentionImpl::forward(const AttentionLayer &laye
const infinilm::runtime::Tensor &value,
infinilm::runtime::Tensor &kv_cache,
const infinilm::global_state::AttentionMetadata &attn_metadata,
infinilm::runtime::Runtime &runtime) const {
infinilm::runtime::Runtime &runtime,
bool pre_transpose) const {
runtime.assertOwnerThread();
if (!query || !key || !value || !kv_cache) {
throw std::invalid_argument("Flash Attention requires non-null Q/K/V and KV cache tensors");
Expand Down Expand Up @@ -70,14 +71,23 @@ infinilm::runtime::Tensor FlashAttentionImpl::forward(const AttentionLayer &laye
auto attn_output = infinilm::runtime::Tensor::empty(
runtime, {seq_len, num_heads_, head_dim_}, query->dtype());
if (is_prefill) {
const auto prefill_query = pre_transpose && !query->is_contiguous()
? query->contiguous(runtime)
: query;
const auto prefill_block_tables =
pre_transpose && !block_tables.value()->is_contiguous()
? block_tables.value()->contiguous(runtime)
: block_tables.value();
infinilm::execution::submit<infini::ops::FlashAttnVarlenFunc>(
runtime, infinilm::execution::RecordingPolicy::DeviceOnly,
infini::ops::Config::Automatic(),
query, k_total, v_total, input_offsets.value(), cu_seqlens.value(),
std::optional<infinilm::runtime::Tensor>{}, std::optional<infinilm::runtime::Tensor>{block_tables.value()},
prefill_query, k_total, v_total, input_offsets.value(), cu_seqlens.value(),
std::optional<infinilm::runtime::Tensor>{},
std::optional<infinilm::runtime::Tensor>{prefill_block_tables},
static_cast<int64_t>(attn_metadata.max_query_length), static_cast<int64_t>(attn_metadata.max_sequence_length),
0.0, std::optional<double>{scale_}, true, layer.window_size(), 0.0, false, false,
attn_output, std::optional<infinilm::runtime::Tensor>{}, std::optional<infinilm::runtime::Tensor>{});
attn_output, std::optional<infinilm::runtime::Tensor>{},
std::optional<infinilm::runtime::Tensor>{});
INFINILM_TRACE_OP(MultiheadAttentionVarlen, attn_output);
} else {
// FA2 decode path: flash::mha_fwd_kvcache
Expand All @@ -94,8 +104,9 @@ infinilm::runtime::Tensor FlashAttentionImpl::forward(const AttentionLayer &laye
kv_config.set_implementation_index(infini::ops::Config::kAutomaticImplementation);
const std::optional<infinilm::runtime::Tensor> kv_none;
infinilm::execution::submit<infini::ops::FlashAttnWithKvcache>(
runtime, infinilm::execution::RecordingPolicy::DeviceOnly, kv_config,
q_for_fa, k_total, v_total, kv_none, kv_none, kv_none, kv_none,
runtime, infinilm::execution::RecordingPolicy::DeviceOnly,
kv_config, q_for_fa, k_total, v_total, kv_none, kv_none, kv_none,
kv_none,
std::optional<infinilm::runtime::Tensor>{total_sequence_lengths.value()}, kv_none, kv_none,
std::optional<infinilm::runtime::Tensor>{block_tables.value()}, kv_none,
std::optional<double>{scale_}, true, kv_window, double{0.0}, true,
Expand Down
3 changes: 2 additions & 1 deletion csrc/layers/attention/backends/flash_attn.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ class FlashAttentionImpl {
const infinilm::runtime::Tensor &value,
infinilm::runtime::Tensor &kv_cache,
const infinilm::global_state::AttentionMetadata &attn_metadata,
infinilm::runtime::Runtime &runtime) const;
infinilm::runtime::Runtime &runtime,
bool pre_transpose = false) const;

std::tuple<infinilm::runtime::Tensor, infinilm::runtime::Tensor> do_kv_cache_update(const AttentionLayer &layer,
const infinilm::runtime::Tensor key,
Expand Down
31 changes: 26 additions & 5 deletions csrc/runtime/runtime.cc
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,25 @@ void Runtime::releaseDeviceMemory(std::byte *ptr) noexcept {
}
}

void Runtime::releaseDirectDeviceMemory(std::byte *ptr) noexcept {
infini::rt::DeviceGuard device_guard{device_.type(), device_.index()};
if (!device_guard.active() || ptr == nullptr) {
return;
}
try {
const auto status = infini::rt::runtime::StreamSynchronize(stream_);
warn_runtime_cleanup_failure("synchronizing direct device memory release", status);
if (status != infini::rt::runtime::kSuccess) {
return;
}
INFINILM_CHECK_ERROR(infini::rt::runtime::Free(ptr));
} catch (const std::exception &error) {
warn_runtime_cleanup_failure("releasing direct device memory", error.what());
} catch (...) {
warn_runtime_cleanup_failure("releasing direct device memory", "unknown error");
}
}

std::shared_ptr<Memory> Runtime::allocateMemory(size_t size) {
infini::rt::DeviceGuard device_guard{device_.type(), device_.index(), true};
auto runtime = shared_from_this();
Expand All @@ -227,7 +246,7 @@ std::shared_ptr<Memory> Runtime::allocateMemory(size_t size) {
return std::make_shared<Memory>(
data_ptr, size, device_,
[runtime](std::byte *p) { runtime->releaseDeviceMemory(p); },
false, size > 0, runtime); // Zero allocations have no allocator block to pin.
false, size > 0, runtime);
} catch (...) {
runtime->device_memory_allocator_->deallocate(data_ptr);
throw;
Expand All @@ -237,14 +256,16 @@ std::shared_ptr<Memory> Runtime::allocateMemory(size_t size) {
std::shared_ptr<Memory> Runtime::allocateParameterMemory(size_t size) {
infini::rt::DeviceGuard device_guard{device_.type(), device_.index(), true};
auto runtime = shared_from_this();
std::byte *data_ptr = runtime->device_memory_allocator_->allocate_exact(size);
void *raw_ptr = nullptr;
INFINILM_CHECK_ERROR(infini::rt::runtime::Malloc(&raw_ptr, size));
auto data_ptr = static_cast<std::byte *>(raw_ptr);
try {
return std::make_shared<Memory>(
data_ptr, size, device_,
[runtime](std::byte *p) { runtime->releaseDeviceMemory(p); },
false, true, runtime);
[runtime](std::byte *p) { runtime->releaseDirectDeviceMemory(p); },
false, false, runtime);
} catch (...) {
runtime->device_memory_allocator_->deallocate(data_ptr);
INFINILM_CHECK_ERROR(infini::rt::runtime::Free(raw_ptr));
throw;
}
}
Expand Down
1 change: 1 addition & 0 deletions csrc/runtime/runtime.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ class Runtime : public std::enable_shared_from_this<Runtime> {
std::unique_ptr<::infinilm::execution::graph::GraphManager> graph_manager_;

void releaseDeviceMemory(std::byte *ptr) noexcept;
void releaseDirectDeviceMemory(std::byte *ptr) noexcept;
void syncStreamForCleanup() noexcept;

Runtime(Device device);
Expand Down
Loading
Loading