-
Notifications
You must be signed in to change notification settings - Fork 51
Add: L3/L2 host-device mapped region design #861
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ccyywwen
wants to merge
2
commits into
hw-native-sys:main
Choose a base branch
from
ccyywwen:host-device_mapped-region
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
99 changes: 99 additions & 0 deletions
99
...host_device_mapped_region_round_trip/kernels/aiv/host_device_mapped_region_round_trip.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| /* | ||
| * Copyright (c) PyPTO Contributors. | ||
| * 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 <cstdint> | ||
|
|
||
| #include <pto/pto-inst.hpp> | ||
|
|
||
| #ifndef __gm__ | ||
| #define __gm__ | ||
| #endif | ||
| #ifndef __aicore__ | ||
| #define __aicore__ [aicore] | ||
| #endif | ||
|
|
||
| #include "pipe_sync.h" | ||
|
|
||
| static constexpr uint64_t kCacheLineBytes = 64; | ||
| static constexpr uint32_t kMaxPollIters = 1024U; | ||
|
|
||
| static inline __aicore__ void flush_range(volatile __gm__ void *addr, uint64_t size_bytes) { | ||
| #if defined(__CCE_KT_TEST__) || defined(__CCE_AICORE__) || defined(__DAV_C220__) | ||
| uintptr_t start = reinterpret_cast<uintptr_t>(addr) & ~(uintptr_t(kCacheLineBytes) - 1u); | ||
| uintptr_t end = | ||
| (reinterpret_cast<uintptr_t>(addr) + size_bytes + kCacheLineBytes - 1u) & ~(uintptr_t(kCacheLineBytes) - 1u); | ||
| for (uintptr_t p = start; p < end; p += kCacheLineBytes) { | ||
| dcci((__gm__ int32_t *)p, SINGLE_CACHE_LINE, CACHELINE_OUT); | ||
| } | ||
| #if defined(__CPU_SIM) | ||
| dsb(0); | ||
| #else | ||
| dsb(DSB_DDR); | ||
| #endif | ||
| pipe_barrier(PIPE_ALL); | ||
| #else | ||
| (void)addr; | ||
| (void)size_bytes; | ||
| __asm__ __volatile__("" ::: "memory"); | ||
| #endif | ||
| } | ||
|
|
||
| static inline __aicore__ void invalidate_range(volatile __gm__ void *addr, uint64_t size_bytes) { | ||
| #if defined(__CCE_KT_TEST__) || defined(__CCE_AICORE__) || defined(__DAV_C220__) | ||
| uintptr_t start = reinterpret_cast<uintptr_t>(addr) & ~(uintptr_t(kCacheLineBytes) - 1u); | ||
| uintptr_t end = | ||
| (reinterpret_cast<uintptr_t>(addr) + size_bytes + kCacheLineBytes - 1u) & ~(uintptr_t(kCacheLineBytes) - 1u); | ||
| for (uintptr_t p = start; p < end; p += kCacheLineBytes) { | ||
| dcci((__gm__ int32_t *)p, SINGLE_CACHE_LINE); | ||
| } | ||
| #if defined(__CPU_SIM) | ||
| dsb(0); | ||
| #else | ||
| dsb(DSB_DDR); | ||
| #endif | ||
| #else | ||
| (void)addr; | ||
| (void)size_bytes; | ||
| __asm__ __volatile__("" ::: "memory"); | ||
| #endif | ||
| } | ||
|
|
||
| static inline __aicore__ volatile __gm__ uint32_t *signal_slot(__gm__ uint8_t *signal_base, uint32_t signal_id) { | ||
| return reinterpret_cast<volatile __gm__ uint32_t *>(signal_base + signal_id * kCacheLineBytes); | ||
| } | ||
|
|
||
| extern "C" __aicore__ __attribute__((always_inline)) void kernel_entry(__gm__ int64_t *args) { | ||
| auto *data = reinterpret_cast<__gm__ uint8_t *>(static_cast<uint64_t>(args[0])); | ||
| auto *signal_base = reinterpret_cast<__gm__ uint8_t *>(static_cast<uint64_t>(args[1])); | ||
| auto *signal0 = signal_slot(signal_base, 0); | ||
| auto *signal1 = signal_slot(signal_base, 1); | ||
| uint32_t seq = static_cast<uint32_t>(args[2]); | ||
| uint32_t nbytes = static_cast<uint32_t>(args[3]); | ||
|
|
||
| bool observed = false; | ||
| for (uint32_t i = 0; i < kMaxPollIters; ++i) { | ||
| invalidate_range(signal0, kCacheLineBytes); | ||
| if (*signal0 >= seq) { | ||
| observed = true; | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| invalidate_range(data, nbytes); | ||
| for (uint32_t i = 0; i < nbytes; ++i) { | ||
| uint8_t mask = observed ? static_cast<uint8_t>(seq + i * 3U) : static_cast<uint8_t>(0xA5U); | ||
| data[nbytes + i] = static_cast<uint8_t>(data[i] ^ mask); | ||
| } | ||
| flush_range(data + nbytes, nbytes); | ||
|
|
||
| *signal1 = seq; | ||
| flush_range(signal1, kCacheLineBytes); | ||
| } | ||
36 changes: 36 additions & 0 deletions
36
...ped_region_round_trip/kernels/orchestration/host_device_mapped_region_round_trip_orch.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| /* | ||
| * Copyright (c) PyPTO Contributors. | ||
| * 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 "pto_orchestration_api.h" // NOLINT(build/include_subdir) | ||
|
|
||
| extern "C" { | ||
|
|
||
| __attribute__((visibility("default"))) PTO2OrchestrationConfig | ||
| host_device_mapped_region_round_trip_config(const ChipStorageTaskArgs &orch_args) { | ||
| (void)orch_args; | ||
| return PTO2OrchestrationConfig{.expected_arg_count = 4}; | ||
| } | ||
|
|
||
| __attribute__((visibility("default"))) PTO2OrchestrationConfig | ||
| aicpu_orchestration_config(const ChipStorageTaskArgs &orch_args) { | ||
| return host_device_mapped_region_round_trip_config(orch_args); | ||
| } | ||
|
|
||
| __attribute__((visibility("default"))) void host_device_mapped_region_round_trip_orch(const ChipStorageTaskArgs &orch_args) { | ||
| Arg args; | ||
| args.add_scalar(orch_args.scalar(0)); | ||
| args.add_scalar(orch_args.scalar(1)); | ||
| args.add_scalar(orch_args.scalar(2)); | ||
| args.add_scalar(orch_args.scalar(3)); | ||
| rt_submit_aiv_task(0, args); | ||
| } | ||
|
|
||
| } // extern "C" |
145 changes: 145 additions & 0 deletions
145
examples/a2a3/tensormap_and_ringbuffer/host_device_mapped_region_round_trip/main.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,145 @@ | ||
| #!/usr/bin/env python3 | ||
| # Copyright (c) PyPTO Contributors. | ||
| # 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. | ||
| # ----------------------------------------------------------------------------------------------------------- | ||
| """Host CPU to device NPU round-trip through HostDeviceMappedRegion.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import argparse | ||
| import os | ||
| import sys | ||
| from pathlib import Path | ||
|
|
||
| from simpler.task_interface import ArgDirection, CallConfig, ChipCallable, CoreCallable, TaskArgs | ||
| from simpler.worker import Worker | ||
| from simpler_setup.elf_parser import extract_text_section | ||
| from simpler_setup.kernel_compiler import KernelCompiler | ||
| from simpler_setup.pto_isa import ensure_pto_isa_root | ||
| from simpler_setup.runtime_builder import RuntimeBuilder | ||
|
|
||
|
|
||
| HERE = Path(__file__).resolve().parent | ||
| KERNEL_DIR = HERE / "kernels" | ||
| RUNTIME = "tensormap_and_ringbuffer" | ||
| DEFAULT_DATA_BYTES = 256 | ||
| DEFAULT_ITERS = 10 | ||
|
|
||
|
|
||
| def _build_callable(platform: str) -> ChipCallable: | ||
| kc = KernelCompiler(platform=platform) | ||
| pto_isa_root = ensure_pto_isa_root(clone_protocol="https") | ||
| include_dirs = kc.get_orchestration_include_dirs(RUNTIME) | ||
|
|
||
| incore = kc.compile_incore( | ||
| source_path=str(KERNEL_DIR / "aiv" / "host_device_mapped_region_round_trip.cpp"), | ||
| core_type="aiv", | ||
| pto_isa_root=pto_isa_root, | ||
| extra_include_dirs=include_dirs, | ||
| ) | ||
| if not platform.endswith("sim"): | ||
| incore = extract_text_section(incore) | ||
|
|
||
| orch = kc.compile_orchestration( | ||
| runtime_name=RUNTIME, | ||
| source_path=str(KERNEL_DIR / "orchestration" / "host_device_mapped_region_round_trip_orch.cpp"), | ||
| ) | ||
| return ChipCallable.build( | ||
| signature=[ArgDirection.IN, ArgDirection.IN, ArgDirection.IN, ArgDirection.IN], | ||
| func_name="host_device_mapped_region_round_trip_orch", | ||
| binary=orch, | ||
| children=[(0, CoreCallable.build(signature=[], binary=incore))], | ||
| ) | ||
|
|
||
|
|
||
| def _pattern(seq: int, data_bytes: int) -> bytes: | ||
| return bytes(((seq * 17 + i * 5) & 0xFF) for i in range(data_bytes)) | ||
|
|
||
|
|
||
| def _expected(seq: int, payload: bytes) -> bytes: | ||
| return bytes((b ^ ((seq + i * 3) & 0xFF)) for i, b in enumerate(payload)) | ||
|
|
||
|
|
||
| def run( | ||
| platform: str, | ||
| device_id: int, | ||
| *, | ||
| build: bool = False, | ||
| iters: int = DEFAULT_ITERS, | ||
| data_bytes: int = DEFAULT_DATA_BYTES, | ||
| ) -> None: | ||
| if platform not in {"a2a3sim", "a2a3"}: | ||
| raise ValueError(f"unsupported platform: {platform}") | ||
| if iters <= 0: | ||
| raise ValueError("iters must be positive") | ||
| if data_bytes <= 0: | ||
| raise ValueError("data_bytes must be positive") | ||
|
|
||
| os.environ["PTO_ISA_ROOT"] = ensure_pto_isa_root(clone_protocol="https") | ||
| RuntimeBuilder(platform=platform).get_binaries(RUNTIME, build=build) | ||
| chip_callable = _build_callable(platform) | ||
|
|
||
| worker = Worker(level=2, platform=platform, runtime=RUNTIME, device_id=device_id, build=build) | ||
| worker.init() | ||
| region = None | ||
| try: | ||
| chip_cid = worker.register(chip_callable) | ||
| region = worker.open_mapped_region(data_bytes * 2, signal_count=2) | ||
| info = worker.mapped_region_info(region) | ||
| assert info.host_data_ptr == 0 | ||
| assert info.host_signal_ptr == 0 | ||
| assert info.device_data_ptr != 0 | ||
| assert info.device_signal_ptr != 0 | ||
|
|
||
| cfg = CallConfig() | ||
| cfg.block_dim = 1 | ||
| cfg.aicpu_thread_num = 2 | ||
|
|
||
| for seq in range(1, iters + 1): | ||
| payload = _pattern(seq, data_bytes) | ||
| worker.mapped_region_datacopy_h2region(region, 0, payload) | ||
| worker.mapped_region_notify(region, 0, seq) | ||
|
|
||
| args = TaskArgs() | ||
| args.add_scalar(info.device_data_ptr) | ||
| args.add_scalar(info.device_signal_ptr) | ||
| args.add_scalar(seq) | ||
| args.add_scalar(data_bytes) | ||
| worker.run(chip_cid, args, cfg) | ||
|
|
||
| worker.mapped_region_wait(region, 1, seq, 1_000_000) | ||
| got = worker.mapped_region_datacopy_region2h(region, data_bytes, data_bytes) | ||
| assert got == _expected(seq, payload) | ||
| finally: | ||
| if region is not None: | ||
| worker.close_mapped_region(region) | ||
| worker.close() | ||
|
|
||
|
|
||
| def parse_args() -> argparse.Namespace: | ||
| parser = argparse.ArgumentParser(description=__doc__) | ||
| parser.add_argument("-p", "--platform", required=True, choices=["a2a3sim", "a2a3"]) | ||
| parser.add_argument("-d", "--device", type=int, default=0) | ||
| parser.add_argument("--build", action="store_true", help="Rebuild runtime from source.") | ||
| parser.add_argument("--iters", type=int, default=DEFAULT_ITERS) | ||
| parser.add_argument("--data-bytes", type=int, default=DEFAULT_DATA_BYTES) | ||
| return parser.parse_args() | ||
|
|
||
|
|
||
| def main() -> int: | ||
| args = parse_args() | ||
| run(args.platform, args.device, build=args.build, iters=args.iters, data_bytes=args.data_bytes) | ||
| print( | ||
| "[host_device_mapped_region_round_trip] " | ||
| f"platform={args.platform} device={args.device} iters={args.iters} data_bytes={args.data_bytes} PASSED" | ||
| ) | ||
| return 0 | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| sys.exit(main()) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Don't signal success after the poll loop times out.
If
signal0never reachesseq, this still writes transformed output and then publishessignal1 = seq. That hides real notify/cache failures and can make the host accept corrupted data as a successful round trip. Bail out, or publish a distinct error sentinel, instead of reusing the success signal.🤖 Prompt for AI Agents