Repository navigation
Expand file tree
/
Copy pathruntime.cpp
More file actions
411 lines (364 loc) · 18.1 KB
/
Copy pathruntime.cpp
File metadata and controls
411 lines (364 loc) · 18.1 KB
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
/**
* Copyright (c) 2026 Huawei Technologies Co., Ltd.
* This program is free software, you can redistribute it and/or modify it under the terms and conditions of
* CANN Open Software License Agreement Version 2.0 (the "License").
* Please refer to the License for details. You may not use this file except in compliance with the License.
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
* See LICENSE in the root of the software repository for the full text of the License.
*/
#include "runtime/runtime.h"
#include <cinttypes>
#include <optional>
#include <string>
#include <utility>
#include "cann/host.h"
#include "runtime/log.h"
namespace hyper_multicore::shmem::runtime {
namespace {
constexpr int32_t kUnavailableRootRank = -1;
Status MakeError(ErrorCode error_code, std::string message) {
return Status{error_code, std::nullopt, std::move(message)};
}
const char *StateName(State state) {
switch (state) {
case State::Uninitialized:
return "Uninitialized";
case State::Ready:
return "Ready";
case State::ShutdownFailed:
return "ShutdownFailed";
}
return "Unknown";
}
const char *DataEngineName(DataEngine engine) { return engine == DataEngine::Mte ? "mte" : "unknown"; }
DfxPhase PhaseForDeviceStatus(const Status &status) {
return status.error_code == ErrorCode::CannError || status.error_code == ErrorCode::Timeout ? DfxPhase::CannCall
: DfxPhase::Validation;
}
} // namespace
Runtime &Runtime::Instance() {
static Runtime instance;
return instance;
}
Status Runtime::Initialize(const RootWorldInfo &root, const Config &config,
std::string_view effective_bootstrap_endpoint, std::string_view unique_id) {
std::lock_guard<std::mutex> lock(mutex_);
if (state_ != State::Uninitialized) {
const Status error =
MakeError(ErrorCode::InvalidState, "Runtime state must be Uninitialized for initialization, but got state=" +
std::string(StateName(state_)));
RecordFailure(DfxOperation::Initialize, DfxPhase::Validation, root.root_rank, error, __FILE__, __LINE__);
return error;
}
const Status validation = ValidateInitialInput(root, config, effective_bootstrap_endpoint);
if (validation.error_code != ErrorCode::Ok) {
return FailInitialization(DfxPhase::Validation, root.root_rank, validation, __FILE__, __LINE__);
}
root_.emplace(root);
const auto device_identity = cann::host::query_device_identity();
if (!device_identity.ok()) {
return FailInitialization(DfxPhase::CannCall, root.root_rank, device_identity.error(), __FILE__, __LINE__);
}
device_identity_.emplace(device_identity.value());
if (device_identity_->model == DeviceModel::kAscend950) {
const Status error = MakeError(
ErrorCode::UnsupportedCapability,
"the first Runtime release supports Ascend 910B and 910C, but got soc_name=" + device_identity_->soc_name);
return FailInitialization(DfxPhase::Validation, root.root_rank, error, __FILE__, __LINE__);
}
allocations_.emplace(device_identity_->device_index, next_allocation_id_);
config_.emplace(config);
const cann::InitOptions options{root.root_rank,
root.root_size,
config.heap_size_bytes,
config.timeout_seconds,
config.data_engine,
effective_bootstrap_endpoint,
unique_id};
HP_SM_LOG_DEBUG(root.root_rank, "Initialize", "CannCall", "aclshmemx_init_attr enter");
const Status initialize_status = cann::host::initialize(options);
if (initialize_status.error_code != ErrorCode::Ok) {
Status failure = initialize_status;
const std::string prefix =
"SHMEM initialization failed on NPU device " + std::to_string(device_identity_->device_index) + ": ";
failure.message = prefix + failure.message;
if (failure.log_message.has_value()) {
*failure.log_message = prefix + *failure.log_message;
}
return FailInitialization(DfxPhase::CannCall, root.root_rank, failure, __FILE__, __LINE__);
}
HP_SM_LOG_DEBUG(root.root_rank, "Initialize", "CannCall", "aclshmemx_init_attr ok");
latest_failure_.reset();
leaked_allocations_.clear();
state_ = State::Ready;
HP_SM_LOG_INFO(root.root_rank, "Initialize", "Complete",
"root=%d/%d heap_bytes=%" PRIu64 " timeout_seconds=%u engine=%s bootstrap=%s endpoint=%.*s",
root.root_rank, root.root_size, config.heap_size_bytes, config.timeout_seconds,
DataEngineName(config.data_engine), unique_id.empty() ? "endpoint" : "unique_id",
static_cast<int>(effective_bootstrap_endpoint.size()), effective_bootstrap_endpoint.data());
return Status{};
}
Result<int32_t> Runtime::RootRank() const {
std::lock_guard<std::mutex> lock(mutex_);
const Status state_status = RequireReady();
if (state_status.error_code != ErrorCode::Ok) {
return Result<int32_t>::Failure(state_status);
}
return Result<int32_t>::Success(root_->root_rank);
}
Result<int32_t> Runtime::RootSize() const {
std::lock_guard<std::mutex> lock(mutex_);
const Status state_status = RequireReady();
if (state_status.error_code != ErrorCode::Ok) {
return Result<int32_t>::Failure(state_status);
}
return Result<int32_t>::Success(root_->root_size);
}
Result<DeviceModel> Runtime::QueryDeviceModel() const {
std::lock_guard<std::mutex> lock(mutex_);
const Status state_status = RequireReady();
if (state_status.error_code != ErrorCode::Ok) {
return Result<DeviceModel>::Failure(state_status);
}
return Result<DeviceModel>::Success(device_identity_->model);
}
Status Runtime::ValidateShutdown() {
std::lock_guard<std::mutex> lock(mutex_);
const int32_t root_rank = RootRankForDfx();
const Status state_status = RequireReady();
if (state_status.error_code != ErrorCode::Ok) {
RecordFailure(DfxOperation::Shutdown, DfxPhase::Validation, root_rank, state_status, __FILE__, __LINE__);
return state_status;
}
const Status device_status = ValidateCurrentDeviceLocked();
if (device_status.error_code != ErrorCode::Ok) {
RecordFailure(DfxOperation::Shutdown, PhaseForDeviceStatus(device_status), root_rank, device_status, __FILE__,
__LINE__);
return device_status;
}
if (allocations_->allocated_count() != 0) {
const Status error =
MakeError(ErrorCode::InvalidState,
"All symmetric Allocations must be freed before Runtime shutdown, but got allocated_count=" +
std::to_string(allocations_->allocated_count()) +
", allocated_bytes=" + std::to_string(allocations_->allocated_bytes()));
RecordFailure(DfxOperation::Shutdown, DfxPhase::Validation, root_rank, error, __FILE__, __LINE__);
return error;
}
return Status{};
}
Result<AllocationRecord> Runtime::Allocate(const AllocationSpec &spec) {
std::lock_guard<std::mutex> lock(mutex_);
const int32_t root_rank = RootRankForDfx();
const Status state_status = RequireReady();
if (state_status.error_code != ErrorCode::Ok) {
RecordFailure(DfxOperation::Allocate, DfxPhase::Validation, root_rank, state_status, __FILE__, __LINE__);
return Result<AllocationRecord>::Failure(state_status);
}
const Status validation = allocations_->Validate(spec);
if (validation.error_code != ErrorCode::Ok) {
RecordFailure(DfxOperation::Allocate, DfxPhase::Validation, root_rank, validation, __FILE__, __LINE__);
return Result<AllocationRecord>::Failure(validation);
}
const Status device_status = ValidateCurrentDeviceLocked();
if (device_status.error_code != ErrorCode::Ok) {
RecordFailure(DfxOperation::Allocate, PhaseForDeviceStatus(device_status), root_rank, device_status, __FILE__,
__LINE__);
return Result<AllocationRecord>::Failure(device_status);
}
const bool has_explicit_alignment = spec.alignment_bytes != 0;
const char *allocation_call = has_explicit_alignment ? "aclshmem_align" : "aclshmem_malloc";
HP_SM_LOG_DEBUG(root_rank, "Allocate", "CannCall", "%s enter bytes=%" PRIu64 " alignment=%" PRIu64, allocation_call,
spec.bytes, spec.alignment_bytes);
const auto allocation = has_explicit_alignment ? cann::host::aligned_allocate(spec.alignment_bytes, spec.bytes)
: cann::host::allocate(spec.bytes);
if (!allocation.ok()) {
RecordFailure(DfxOperation::Allocate, DfxPhase::CannCall, root_rank, allocation.error(), __FILE__, __LINE__);
return Result<AllocationRecord>::Failure(allocation.error());
}
const AllocationRecord record = allocations_->Register(spec, allocation.value());
HP_SM_LOG_DEBUG(root_rank, "Allocate", "CannCall", "%s ok allocation_id=%" PRIu64, allocation_call,
record.allocation_id);
return Result<AllocationRecord>::Success(record);
}
Status Runtime::Free(const AllocationView &buffer) {
std::lock_guard<std::mutex> lock(mutex_);
const int32_t root_rank = RootRankForDfx();
const Status state_status = RequireReady();
if (state_status.error_code != ErrorCode::Ok) {
RecordFailure(DfxOperation::Free, DfxPhase::Validation, root_rank, state_status, __FILE__, __LINE__);
return state_status;
}
const auto record = allocations_->MatchForFree(buffer);
if (!record.ok()) {
RecordFailure(DfxOperation::Free, DfxPhase::Validation, root_rank, record.error(), __FILE__, __LINE__);
return record.error();
}
const Status device_status = ValidateCurrentDeviceLocked();
if (device_status.error_code != ErrorCode::Ok) {
RecordFailure(DfxOperation::Free, PhaseForDeviceStatus(device_status), root_rank, device_status, __FILE__,
__LINE__);
return device_status;
}
HP_SM_LOG_DEBUG(root_rank, "Free", "CannCall", "aclshmem_free enter allocation_id=%" PRIu64, buffer.allocation_id);
cann::host::free_memory(record.value().allocation_base);
allocations_->Remove(buffer.allocation_id);
HP_SM_LOG_DEBUG(root_rank, "Free", "CannCall", "aclshmem_free ok allocation_id=%" PRIu64, buffer.allocation_id);
return Status{};
}
Result<AllocationRecord> Runtime::ResolveAllocation(const AllocationView &buffer) const {
std::lock_guard<std::mutex> lock(mutex_);
const Status state_status = RequireReady();
if (state_status.error_code != ErrorCode::Ok) {
return Result<AllocationRecord>::Failure(state_status);
}
return allocations_->Resolve(buffer);
}
Status Runtime::Barrier(const StreamView &stream) {
std::lock_guard<std::mutex> lock(mutex_);
const int32_t root_rank = RootRankForDfx();
const Status state_status = RequireReady();
if (state_status.error_code != ErrorCode::Ok) {
RecordFailure(DfxOperation::Barrier, DfxPhase::Validation, root_rank, state_status, __FILE__, __LINE__);
return state_status;
}
if (stream.native_handle == 0 || stream.device_index != device_identity_->device_index) {
const Status error =
MakeError(ErrorCode::InvalidArgument,
"barrier Stream must have a nonzero handle on the Runtime-bound device, but got native_handle=" +
std::to_string(stream.native_handle) + ", device_index=" + std::to_string(stream.device_index) +
", bound device_index=" + std::to_string(device_identity_->device_index));
RecordFailure(DfxOperation::Barrier, DfxPhase::Validation, root_rank, error, __FILE__, __LINE__);
return error;
}
HP_SM_LOG_DEBUG(root_rank, "Barrier", "Enqueue", "aclshmemx_barrier_on_stream enter");
cann::host::barrier_on_stream(stream);
HP_SM_LOG_DEBUG(root_rank, "Barrier", "Enqueue", "aclshmemx_barrier_on_stream ok enqueue_only=true");
return Status{};
}
DfxSnapshot Runtime::DebugState() const {
std::lock_guard<std::mutex> lock(mutex_);
DfxSnapshot snapshot{};
snapshot.state = state_;
snapshot.root = root_;
snapshot.device_identity = device_identity_;
snapshot.config = config_;
snapshot.latest_failure = latest_failure_;
if (allocations_.has_value()) {
snapshot.allocated_count = allocations_->allocated_count();
snapshot.allocated_bytes = allocations_->allocated_bytes();
snapshot.max_allocated_bytes = allocations_->max_allocated_bytes();
snapshot.active_allocations = allocations_->ActiveRecords();
snapshot.leaked_allocations = leaked_allocations_;
}
return snapshot;
}
void Runtime::RecordLeak(uint64_t allocation_id, uintptr_t allocation_base, uint64_t allocation_bytes) {
std::lock_guard<std::mutex> lock(mutex_);
leaked_allocations_.push_back(AllocationRecord{allocation_id, allocation_base, allocation_bytes, 0});
}
Status Runtime::Shutdown() {
std::lock_guard<std::mutex> lock(mutex_);
if (state_ == State::Uninitialized || state_ == State::ShutdownFailed) {
return Status{};
}
if (state_ != State::Ready) {
const Status error = MakeError(ErrorCode::InvalidState, "Runtime state must be Ready for shutdown, but got state=" +
std::string(StateName(state_)));
RecordFailure(DfxOperation::Shutdown, DfxPhase::Validation, RootRankForDfx(), error, __FILE__, __LINE__);
return error;
}
const int32_t root_rank = RootRankForDfx();
const uint64_t allocated_count = allocations_->allocated_count();
const uint64_t allocated_bytes = allocations_->allocated_bytes();
if (allocated_count != 0) {
const Status error =
MakeError(ErrorCode::InvalidState,
"All symmetric Allocations must be freed before Runtime shutdown, but got allocated_count=" +
std::to_string(allocated_count) + ", allocated_bytes=" + std::to_string(allocated_bytes));
RecordFailure(DfxOperation::Shutdown, DfxPhase::Validation, root_rank, error, __FILE__, __LINE__);
return error;
}
HP_SM_LOG_DEBUG(root_rank, "Shutdown", "CannCall", "aclshmem_finalize enter");
const Status finalize_status = cann::host::finalize();
if (finalize_status.error_code != ErrorCode::Ok) {
state_ = State::ShutdownFailed;
RecordFailure(DfxOperation::Shutdown, DfxPhase::CannCall, root_rank, finalize_status, __FILE__, __LINE__);
return finalize_status;
}
HP_SM_LOG_DEBUG(root_rank, "Shutdown", "CannCall", "aclshmem_finalize ok");
next_allocation_id_ = allocations_->next_allocation_id();
HP_SM_LOG_INFO(root_rank, "Shutdown", "Complete",
"mode=finalize active_allocations_at_shutdown=0 active_bytes_at_shutdown=0");
allocations_.reset();
device_identity_.reset();
root_.reset();
config_.reset();
latest_failure_.reset();
leaked_allocations_.clear();
state_ = State::Uninitialized;
return Status{};
}
Status Runtime::ValidateInitialInput(const RootWorldInfo &root, const Config &config,
std::string_view effective_bootstrap_endpoint) const {
if (root.root_size <= 0 || root.root_rank < 0 || root.root_rank >= root.root_size) {
return MakeError(ErrorCode::InvalidArgument,
"root_rank must be in [0, root_size) and root_size must be positive, but got root_rank=" +
std::to_string(root.root_rank) + ", root_size=" + std::to_string(root.root_size));
}
if (config.heap_size_bytes == 0 || config.timeout_seconds == 0 || config.data_engine != DataEngine::Mte) {
return MakeError(ErrorCode::InvalidConfig,
"Runtime Config requires positive heap/timeout values and the MTE data engine");
}
if (config.bootstrap_endpoint_base.empty() || config.bootstrap_endpoint_base.size() > kMaxBootstrapEndpointBytes) {
return MakeError(ErrorCode::InvalidConfig, "bootstrap_endpoint_base must contain between 1 and " +
std::to_string(kMaxBootstrapEndpointBytes) + " bytes, but got size=" +
std::to_string(config.bootstrap_endpoint_base.size()));
}
if (effective_bootstrap_endpoint.empty() || effective_bootstrap_endpoint.size() > kMaxBootstrapEndpointBytes) {
return MakeError(ErrorCode::InvalidArgument,
"effective_bootstrap_endpoint must contain between 1 and " +
std::to_string(kMaxBootstrapEndpointBytes) +
" bytes, but got size=" + std::to_string(effective_bootstrap_endpoint.size()));
}
return Status{};
}
Status Runtime::ValidateCurrentDeviceLocked() const {
const auto current_device = cann::host::query_current_device_index();
if (!current_device.ok()) {
return current_device.error();
}
if (current_device.value() != device_identity_->device_index) {
return MakeError(ErrorCode::InvalidArgument,
"Current ACL device must match the Runtime-bound device, but got current device_index=" +
std::to_string(current_device.value()) +
", bound device_index=" + std::to_string(device_identity_->device_index));
}
return Status{};
}
Status Runtime::RequireReady() const {
if (state_ != State::Ready) {
return MakeError(ErrorCode::InvalidState,
"Runtime state must be Ready for this operation, but got state=" + std::string(StateName(state_)));
}
return Status{};
}
int32_t Runtime::RootRankForDfx() const noexcept { return root_.has_value() ? root_->root_rank : kUnavailableRootRank; }
void Runtime::RecordFailure(DfxOperation operation, DfxPhase phase, int32_t root_rank, const Status &error,
const char *file, int line) {
latest_failure_.emplace(DfxFailure{operation, phase, root_rank, error});
log::Failure(file, line, *latest_failure_);
}
Status Runtime::FailInitialization(DfxPhase phase, int32_t root_rank, const Status &error, const char *file, int line) {
// Roll back the partially initialized lifecycle so the caller can retry: CANN rolls its own initialization
// failure back, so no CANN finalize is needed or allowed here.
allocations_.reset();
config_.reset();
root_.reset();
device_identity_.reset();
leaked_allocations_.clear();
RecordFailure(DfxOperation::Initialize, phase, root_rank, error, file, line);
return error;
}
} // namespace hyper_multicore::shmem::runtime