Skip to content

Commit ccf19fb

Browse files
committed
perf(ascend): add validated graph and prefill optimizations
1 parent 3073b3d commit ccf19fb

30 files changed

Lines changed: 1698 additions & 103 deletions

File tree

‎include/infinicore/graph/graph.hpp‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ enum class GraphReplayStage {
1515
CAPTURE_BEGIN,
1616
CAPTURE_END,
1717
UPDATE,
18+
PREPARE_UPDATE,
19+
ABORT_UPDATE,
1820
};
1921
using graph_replay_schema = void (*)(void *, GraphReplayStage);
2022

@@ -35,6 +37,9 @@ class GraphOperator {
3537
virtual void graph_replay(GraphReplayStage) const {
3638
}
3739
virtual ~GraphOperator() = default;
40+
virtual bool can_update_after_launch() const {
41+
return false;
42+
}
3843
};
3944

4045
class DispatchableGraphOperator : public GraphOperator {
@@ -43,17 +48,22 @@ class DispatchableGraphOperator : public GraphOperator {
4348
bool needs_graph_replay_update() const override;
4449
void graph_replay(GraphReplayStage stage) const override;
4550
~DispatchableGraphOperator() override;
51+
bool can_update_after_launch() const override {
52+
return graph_replay_launch_first_;
53+
}
4654

4755
protected:
48-
void set_graph_replay_handler(graph_replay_schema handler) {
56+
void set_graph_replay_handler(graph_replay_schema handler, bool launch_first = false) {
4957
graph_replay_ = handler;
58+
graph_replay_launch_first_ = launch_first;
5059
}
5160
using run_schema = void (*)(void *);
5261
using cleanup_schema = void (*)(void **);
5362
void *planned_meta_;
5463
run_schema runner_;
5564
cleanup_schema deleter_;
5665
graph_replay_schema graph_replay_ = nullptr;
66+
bool graph_replay_launch_first_ = false;
5767
};
5868

5969
class Graph {
@@ -65,6 +75,9 @@ class Graph {
6575
void bind_host_int_array(const Tensor &device_tensor,
6676
const int32_t *values,
6777
size_t size);
78+
void bind_host_int_array(const Tensor &device_tensor,
79+
const int64_t *values,
80+
size_t size);
6881

6982
protected:
7083
void add_operator(std::shared_ptr<GraphOperator> op);
@@ -85,6 +98,9 @@ void clear_eager_host_int_arrays();
8598
void bind_eager_host_int_array(const Tensor &device_tensor,
8699
const int32_t *values,
87100
size_t size);
101+
void bind_eager_host_int_array(const Tensor &device_tensor,
102+
const int64_t *values,
103+
size_t size);
88104
} // namespace infinicore::graph
89105

90106
#define INFINICORE_GRAPH_OP_CLASS(__OP_NAME__, ...) \
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#pragma once
2+
#include "../graph/graph.hpp"
3+
#include "common/op.hpp"
4+
namespace infinicore::op {
5+
INFINICORE_GRAPH_OP_CLASS(ApplyRoPE, Tensor, Tensor, const Tensor &, const Tensor &);
6+
// In-place NeoX rotation of contiguous TND Q/K using full-width cos/sin.
7+
void apply_rope_(Tensor q, Tensor k, const Tensor &cos, const Tensor &sin);
8+
} // namespace infinicore::op

‎include/infiniop.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
#include "infiniop/ops/adaptive_avg_pool3d.h"
88
#include "infiniop/ops/adaptive_max_pool1d.h"
99
#include "infiniop/ops/add.h"
10+
#include "infiniop/ops/apply_rope.h"
1011
#include "infiniop/ops/add_rms_norm.h"
1112
#include "infiniop/ops/addbmm.h"
1213
#include "infiniop/ops/addcmul.h"

‎include/infiniop/ops/apply_rope.h‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
#ifndef __INFINIOP_APPLY_ROPE_API_H__
2+
#define __INFINIOP_APPLY_ROPE_API_H__
3+
#include "../operator_descriptor.h"
4+
typedef struct InfiniopDescriptor *infiniopApplyRoPEDescriptor_t;
5+
// Ascend NeoX rotation, in place. All tensors must be contiguous, with the
6+
// same F16/BF16/F32 dtype. Q/K are [T,H,D], cos/sin [T,1,D], D=64 or 128.
7+
// Q and K buffers must not overlap. The supplied cos/sin repeat both halves.
8+
__INFINI_C __export infiniStatus_t infiniopCreateApplyRoPEDescriptor(
9+
infiniopHandle_t handle, infiniopApplyRoPEDescriptor_t *desc,
10+
infiniopTensorDescriptor_t q, infiniopTensorDescriptor_t k,
11+
infiniopTensorDescriptor_t cos, infiniopTensorDescriptor_t sin);
12+
__INFINI_C __export infiniStatus_t infiniopGetApplyRoPEWorkspaceSize(
13+
infiniopApplyRoPEDescriptor_t desc, size_t *size);
14+
__INFINI_C __export infiniStatus_t infiniopApplyRoPE(
15+
infiniopApplyRoPEDescriptor_t desc, void *workspace, size_t workspace_size,
16+
void *q, void *k, const void *cos, const void *sin, void *stream);
17+
__INFINI_C __export infiniStatus_t infiniopDestroyApplyRoPEDescriptor(
18+
infiniopApplyRoPEDescriptor_t desc);
19+
#endif

‎include/infiniop/ops/paged_caching.h‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,23 @@ __INFINI_C __export infiniStatus_t infiniopCreatePagedCachingDescriptor(
3030
infiniopTensorDescriptor_t v_desc,
3131
infiniopTensorDescriptor_t slot_mapping_desc);
3232

33+
/**
34+
* @brief Create a cache descriptor for caller-validated slot mappings.
35+
*
36+
* The caller must verify all slots are nonnegative, below cache capacity,
37+
* and unique on every invocation. Ascend may use ACLNN for contiguous ND
38+
* layouts. Use the ordinary descriptor for padding slots or device graphs
39+
* whose slot values can change without being revalidated.
40+
*/
41+
__INFINI_C __export infiniStatus_t infiniopCreatePagedCachingWithValidSlotsDescriptor(
42+
infiniopHandle_t handle,
43+
infiniopPagedCachingDescriptor_t *desc_ptr,
44+
infiniopTensorDescriptor_t k_cache_desc,
45+
infiniopTensorDescriptor_t v_cache_desc,
46+
infiniopTensorDescriptor_t k_desc,
47+
infiniopTensorDescriptor_t v_desc,
48+
infiniopTensorDescriptor_t slot_mapping_desc);
49+
3350
/**
3451
* @brief Retrieves the workspace size required for the Paged Caching operation.
3552
*

‎src/infinicore/graph/graph.cc‎

Lines changed: 67 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22

33
#include "../utils.hpp"
44
#include "infinicore/context/context.hpp"
5+
#include <algorithm>
56
#include <cstdlib>
7+
#include <cstring>
68
#include <infinirt.h>
79

810
namespace infinicore::graph {
@@ -98,10 +100,40 @@ struct Graph::Segment {
98100

99101
void run() const {
100102
if (device_graph) {
101-
for (const auto &op : device_graph->updatable_ops) {
102-
op->graph_replay(GraphReplayStage::UPDATE);
103+
const auto &updates = device_graph->updatable_ops;
104+
const bool launch_first = !updates.empty()
105+
&& std::all_of(updates.begin(), updates.end(), [](const auto &op) {
106+
return op->can_update_after_launch();
107+
});
108+
if (launch_first) {
109+
// Reusing update handles requires the preceding replay to have
110+
// finished. In token generation this stream is already drained
111+
// by sampling; standalone asynchronous callers remain safe too.
112+
context::syncStream();
113+
for (const auto &op : updates) {
114+
op->graph_replay(GraphReplayStage::PREPARE_UPDATE);
115+
}
116+
device_graph->launch();
117+
try {
118+
for (const auto &op : updates) {
119+
op->graph_replay(GraphReplayStage::UPDATE);
120+
}
121+
} catch (...) {
122+
// Release captured waits before propagating a failed update.
123+
// No output from this replay may be consumed by the caller.
124+
for (const auto &op : updates) {
125+
try {
126+
op->graph_replay(GraphReplayStage::ABORT_UPDATE);
127+
} catch (...) {}
128+
}
129+
throw;
130+
}
131+
} else {
132+
for (const auto &op : updates) {
133+
op->graph_replay(GraphReplayStage::UPDATE);
134+
}
135+
device_graph->launch();
103136
}
104-
device_graph->launch();
105137
return;
106138
}
107139
for (const auto &op : ops) {
@@ -140,6 +172,20 @@ void Graph::bind_host_int_array(const Tensor &device_tensor,
140172
}
141173
}
142174

175+
void Graph::bind_host_int_array(const Tensor &device_tensor,
176+
const int64_t *values,
177+
size_t size) {
178+
INFINICORE_ASSERT(device_tensor);
179+
INFINICORE_ASSERT(values != nullptr || size == 0);
180+
181+
auto &bound = host_int_arrays_[device_tensor->data()];
182+
bound.clear();
183+
bound.reserve(size);
184+
for (size_t i = 0; i < size; ++i) {
185+
bound.push_back(values[i]);
186+
}
187+
}
188+
143189
const std::vector<int64_t> *lookup_bound_host_int_array(const Tensor &tensor) {
144190
if (!tensor) {
145191
return nullptr;
@@ -174,6 +220,18 @@ void bind_eager_host_int_array(const Tensor &device_tensor,
174220
}
175221
}
176222

223+
void bind_eager_host_int_array(const Tensor &device_tensor,
224+
const int64_t *values,
225+
size_t size) {
226+
INFINICORE_ASSERT(device_tensor);
227+
INFINICORE_ASSERT(values != nullptr || size == 0);
228+
auto &bound = eager_host_int_arrays[device_tensor->data()];
229+
bound.clear();
230+
if (size != 0) {
231+
bound.assign(values, values + size);
232+
}
233+
}
234+
177235
void Graph::add_operator(std::shared_ptr<GraphOperator> op) {
178236
op_list_.push_back(op);
179237
}
@@ -182,8 +240,14 @@ void Graph::instantiate() {
182240
segments_.clear();
183241

184242
// Warm the complete op list before splitting it into replay segments.
243+
const char *sync_warmup = std::getenv("INFINICORE_GRAPH_SYNC_WARMUP");
185244
for (size_t iter = 0; iter < 5; ++iter) {
186245
this->run();
246+
// Optional bounded submission for communication backends with a
247+
// process-wide launch cache lock. Runtime graph replay is unchanged.
248+
if (sync_warmup && std::strcmp(sync_warmup, "1") == 0) {
249+
context::syncStream();
250+
}
187251
}
188252
infinicore::context::syncStream();
189253

‎src/infinicore/nn/rope.cc‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
11
#include "infinicore/nn/rope.hpp"
22
#include "../../utils.h"
33
#include "../utils.hpp"
4+
#include "infinicore/ops/apply_rope.hpp"
5+
#include "infinicore/ops/embedding.hpp"
46
#include "infinicore/ops/mrope.hpp"
57
#include "infinicore/ops/rope.hpp"
68
#include "infinicore/ops/rotary_embedding.hpp"
79
#include <algorithm>
810
#include <cassert>
911
#include <cmath>
12+
#include <cstdlib>
13+
#include <cstring>
1014
#include <functional>
1115
#include <stdexcept>
1216
#include <utility>
@@ -178,6 +182,20 @@ void RoPE::initialize_cache() {
178182
"RoPE cache dtype conversion not yet supported for dtype: "
179183
+ std::to_string(static_cast<int>(dtype_)));
180184
}
185+
const char *apply_rope = std::getenv("INFINICORE_ASCEND_APPLY_ROPE");
186+
if (device_.getType() == Device::Type::ASCEND && !mrope_section_
187+
&& algo_ == Algo::GPT_NEOX && rotary_dim_ == head_dim_
188+
&& (head_dim_ == 64 || head_dim_ == 128)
189+
&& apply_rope && std::strcmp(apply_rope, "1") == 0) {
190+
// Prepare full-width NeoX cos/sin once. Each half repeats the same
191+
// frequencies; use strided copies, never per-row D2D submissions.
192+
auto full = Tensor::empty({max_seq_len_, rotary_dim_ * 2}, dtype_, device_);
193+
for (size_t offset : {size_t{0}, cache_dim}) {
194+
full->narrow({{1, offset, cache_dim}})->copy_from(cos_cache_);
195+
full->narrow({{1, rotary_dim_ + offset, cache_dim}})->copy_from(sin_cache_);
196+
}
197+
register_buffer("aclnn_apply_cos_sin_cache", full);
198+
}
181199
}
182200

183201
Tensor RoPE::forward(const Tensor &x, const Tensor &pos, bool in_place) const {
@@ -279,6 +297,35 @@ std::pair<Tensor, Tensor> RoPE::forward(const Tensor &q_out,
279297
const Tensor &k,
280298
const Tensor &positions) const {
281299
if (!mrope_section_.has_value()) {
300+
auto compatible = [this](const Tensor &t) {
301+
const size_t rank = t->ndim();
302+
return (rank == 3 || (rank == 4 && t->size(0) == 1))
303+
&& t->size(rank - 1) == head_dim_
304+
&& t->stride(rank - 1) == 1
305+
&& t->stride(rank - 2) == static_cast<ptrdiff_t>(head_dim_);
306+
};
307+
308+
const char *apply_flag = std::getenv("INFINICORE_ASCEND_APPLY_ROPE");
309+
const auto full_cache = buffers_.find("aclnn_apply_cos_sin_cache");
310+
if (device_.getType() == Device::Type::ASCEND && apply_flag
311+
&& std::strcmp(apply_flag, "1") == 0 && full_cache != buffers_.end()
312+
&& positions->ndim() == 1 && positions->dtype() == DataType::I64
313+
&& positions->is_contiguous() && compatible(q) && compatible(k)
314+
&& q_out->is_contiguous() && k_out->is_contiguous()) {
315+
const auto tokens = positions->size(0);
316+
auto rows = op::embedding(positions, full_cache->second);
317+
auto cos = rows->narrow({{1, 0, rotary_dim_}})->contiguous()->view({tokens, 1, rotary_dim_});
318+
auto sin = rows->narrow({{1, rotary_dim_, rotary_dim_}})->contiguous()->view({tokens, 1, rotary_dim_});
319+
auto mutable_q_out = q_out;
320+
auto mutable_k_out = k_out;
321+
mutable_q_out->copy_from(q);
322+
mutable_k_out->copy_from(k);
323+
const auto q_rank = q_out->ndim(), k_rank = k_out->ndim();
324+
auto qo = q_out->view({tokens, q_out->size(q_rank - 2), head_dim_});
325+
auto ko = k_out->view({tokens, k_out->size(k_rank - 2), head_dim_});
326+
op::apply_rope_(qo, ko, cos, sin);
327+
return {q_out, k_out};
328+
}
282329
#ifdef ENABLE_INFINIOPS_API
283330
if (cos_sin_cache_) {
284331
auto mutable_q_out = q_out;
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#include "infinicore/ops/apply_rope.hpp"
2+
#include "../../utils.hpp"
3+
namespace infinicore::op {
4+
INFINICORE_GRAPH_OP_DISPATCHERS_IMPL(ApplyRoPE);
5+
ApplyRoPE::ApplyRoPE(Tensor q, Tensor k, const Tensor &cos, const Tensor &sin) {
6+
INFINICORE_ASSERT_TENSORS_SAME_DEVICE(q, k, cos, sin);
7+
INFINICORE_GRAPH_OP_DISPATCH(q->device().getType(), q, k, cos, sin);
8+
}
9+
void ApplyRoPE::execute(Tensor q, Tensor k, const Tensor &cos, const Tensor &sin) {
10+
INFINICORE_GRAPH_OP_RECORD_OR_RUN(ApplyRoPE, q, k, cos, sin);
11+
}
12+
void apply_rope_(Tensor q, Tensor k, const Tensor &cos, const Tensor &sin) {
13+
ApplyRoPE::execute(q, k, cos, sin);
14+
}
15+
} // namespace infinicore::op
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#include "../infiniop_impl.hpp"
2+
#include "infinicore/ops/apply_rope.hpp"
3+
namespace infinicore::op::apply_rope_impl::infiniop {
4+
INFINIOP_CACHABLE_DESCRIPTOR(Descriptor, ApplyRoPE, 100);
5+
struct PlannedMeta {
6+
std::shared_ptr<Descriptor> descriptor;
7+
graph::GraphTensor workspace, q, k, cos, sin;
8+
};
9+
void *plan(Tensor q, Tensor k, const Tensor &cos, const Tensor &sin) {
10+
const size_t seed = hash_combine(q, k, cos, sin);
11+
INFINIOP_CACHABLE_DESCRIPTOR_GET_OR_CREATE(Descriptor, descriptor, ApplyRoPE,
12+
seed, q->desc(), k->desc(), cos->desc(), sin->desc());
13+
INFINIOP_WORKSPACE_TENSOR(workspace, ApplyRoPE, descriptor);
14+
return new PlannedMeta{descriptor, graph::GraphTensor(workspace),
15+
graph::GraphTensor(q), graph::GraphTensor(k),
16+
graph::GraphTensor(cos), graph::GraphTensor(sin)};
17+
}
18+
void run(void *meta) {
19+
auto *p = reinterpret_cast<PlannedMeta *>(meta);
20+
INFINICORE_CHECK_ERROR(infiniopApplyRoPE(p->descriptor->desc,
21+
p->workspace->data(), p->workspace->numel(), p->q->data(), p->k->data(),
22+
p->cos->data(), p->sin->data(), context::getStream()));
23+
}
24+
void cleanup(void **meta) {
25+
delete *reinterpret_cast<PlannedMeta **>(meta);
26+
*meta = nullptr;
27+
}
28+
static bool registered = []() {
29+
ApplyRoPE::plan_dispatcher().registerDevice(Device::Type::ASCEND, &plan);
30+
ApplyRoPE::run_dispatcher().registerDevice(Device::Type::ASCEND, &run);
31+
ApplyRoPE::cleanup_dispatcher().registerDevice(Device::Type::ASCEND, &cleanup);
32+
return true;
33+
}();
34+
} // namespace infinicore::op::apply_rope_impl::infiniop

0 commit comments

Comments
 (0)